顺时针打印矩阵
2015-12-29 20:41
288 查看
题目描述:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵:1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
输入:
输入可能包含多个测试样例,对于每个测试案例,
输入的第一行包括两个整数m和n(1<=m,n<=1000):表示矩阵的维数为m行n列。
接下来的m行,每行包括n个整数,表示矩阵的元素,其中每个元素a的取值范围为(1<=a<=10000)。
输出:
对应每个测试案例,输出一行,
按照从外向里以顺时针的顺序依次打印出每一个数字,每个数字后面都有一个空格。
样例输入:
4 4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
样例输出:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
回到顶部
解题思路:
这道题目有一个坑人的地方,但是题目中已经说明了,就是每个数字后面都有一个空格,因此,最后一个数字也是有空格的。主要的思想是:采用一层一层的剥离输出。我们标记好每次行threshold_m与列threshold_n的范围,然后通过指定输出的顶点,来调用输出函数。
#include <stdio.h> #define MAXSIZE 1000 int arr[MAXSIZE][MAXSIZE] = {0}; int threshold_m = 0; int threshold_n = 0; void printMatrix(int m,int n); int main(){ int m,n,i,j; while(scanf("%d %d",&m,&n) != EOF && n>=1 && n<=1000 && m>=1 && m<=1000){ for(i=0; i<m; i++){ for(j=0; j<n; j++) scanf("%d",&arr[i][j]); } threshold_n = n; threshold_m = m; i=0; j=0; while(i<threshold_m && j < threshold_n){ printMatrix(i,j); i++; j++; threshold_n--; threshold_m--; } printf("\n"); } return 0; } void printMatrix(int m,int n){ int i=m,j=n; for( ;j<threshold_n;j++){ printf("%d ",arr[i][j]); } j--; for(i++;i<threshold_m;i++){ printf("%d ",arr[i][j]); } i--; for(j--;j>=n && i!=m;j--){ printf("%d ",arr[i][j]); } j++; for(i--;i>m && j!=threshold_n-1;i--){ printf("%d ",arr[i][j]); } }
转载地址:/article/4686157.html
相关文章推荐
- mysql之控制行操作(一)
- mac重启需要多次输入钥匙串密码的问题
- yum安装node.js
- iOS小程序-混合计算器
- 《Monkey Android》第7课RelativeLayout、TableLayout
- Js清除Cookie
- 信息竞赛学习笔记:POJ3579中位数(二分)
- OpenJudge_P4979 海贼王之伟大航路(状态压缩DP)
- spark streaming 1.5.2 编程指南
- java中Object源码分析
- Hadoop学习指南
- ElasticSearch的Gateway及存储原理
- SQL解析有两个,号分隔的字符串方法
- 《Monkey Android》第6课点击事件的四种写法
- android基础学习之ContentProvider
- 响应式网站设计与制作
- springmvc 国际化
- jquery复制dom对象,不复制事件的问题
- 12月29日-Eclipse的熟悉
- PHP 连接打开新网页带参数