顺时针打印矩阵
做一个题目练练手吧,这题还是蛮有意思的。
题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
例如:如果输入如下矩阵:
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。
没什么算法以及其他高深的东西,就是边界判断和细心。
我的解法如下:
#include<stdio.h> #include<stdlib.h> void print_array(int y,int x,int** array) { int x_start = 0; int y_start = 0; int x_end = x-1; int y_end = y-1; while(x_start<=x_end && y_start<=y_end) { if(x_start == x_end) { while(y_start<=y_end) printf("%d ",array[y_start++][x_start]); break; } else if(y_start == y_end) { while(x_start<=x_end) printf("%d ",array[y_start][x_start++]); break; } else { int x_now = x_start; int y_now = y_start; //right while(x_now<=x_end) printf("%d ",array[y_now][x_now++]); x_now=x_end; //down y_now++; while(y_now<=y_end) printf("%d ",array[y_now++][x_now]); y_now = y_end; //left x_now--; while(x_now>=x_start) printf("%d ",array[y_now][x_now--]); x_now=x_start; //up y_now--; while(y_now>y_start) printf("%d ",array[y_now--][x_now]); //new start x_start +=1; x_end-=1; y_start+=1; y_end-=1; } } printf("\n"); } int main() { int row,column; printf("Please input the row and column:"); while(scanf("%d %d",&row,&column)!=EOF) { int ** array = malloc(sizeof(int*)*row); int i,j; int add =1; for(i=0;i<row;i++) { array[i]=malloc(sizeof(int)*column); for(j=0;j<column;j++) { array[i][j]=add++; printf("%04d ",array[i][j]); } printf("\n"); } print_array(row,column,array); for(i=0;i<row;i++) free(array[i]); free(array); } return 0; }
有一个问题,就是关于x,y坐标的问题。我总是将二维数组的行看成x坐标轴,而列看成y坐标轴,但对应于坐标(x,y)的数组元素是
array[y][x].这个以后一定要注意了啊!!!
附上我的测试用例和测试结果的地址:
posted on 2010-12-24 15:43 Weifeng Wang 阅读(1745) 评论(1) 编辑 收藏 举报