題目描述:順時針打印一個任意arr[line][row]矩陣,如:
思路:順時針打印 第一圈
先向右打印 arr[0][0] --->arr[0][row-1]
再向下打印 arr[1][row-1]--->arr[line-1][row-1]
再向左打印 arr[line-1][row-2]--->arr[line-1][0]
最後向上打印 arr[line-2][0]--->arr[1][0]
然後第n圈從arr[n][n]為第一個元素開始,直至結束,可用cnt計數做跳出條件,因為num <= line * row
當不是m階矩陣時,共有n圈 n = (line < row? line:row)/2
val 為每圈循環下來大小減2
注:不同於用起始坐標定位
#include<stdio.h> #include<stdlib.h> #define line 5 #define row 4 int main(int argc,char* argv[]) { int j,i,num,n,val; int arr[line][row] = {0}; val = line < row ? line : row; n = 0; num = 1; for(val;val > 0;val -=2,n ++) { for(i = n,j = n;(i < line - n )&& (num <= line * row );i ++,num ++) arr[i][j] = num; for(-- i,++ j;(j < row - n )&& (num <= line * row );j ++,num ++) arr[i][j] = num; for(--i,--j;(i >= n )&& (num <= line * row );i --,num ++) arr[i][j] = num; for(++ i,--j;(j > n )&& (num <= line * row );j --,num ++) arr[i][j] = num; } for(i = 0;i < line;i++) { for(j = 0;j < row;j++) printf("%4d",arr[i][j]); printf("\n"); } system("pause"); return 0; }
逆時針:
#include<stdio.h> #include<stdlib.h> #define line 5 #define row 5 int main(int argc,char* argv[]) { int j,i,num,n,val; int arr[line][row] = {0}; val = line < row ? line : row; n = 0; num = 1; for(val;val > 0;val -=2,n ++) { for(i = n,j = n;(i < line - n )&& (num <= line * row );i ++,num ++) arr[i][j] = num; for(-- i,++ j;(j < row - n )&& (num <= line * row );j ++,num ++) arr[i][j] = num; for(--i,--j;(i >= n )&& (num <= line * row );i --,num ++) arr[i][j] = num; for(++ i,--j;(j > n )&& (num <= line * row );j --,num ++) arr[i][j] = num; } for(i = 0;i < line;i++) { for(j = 0;j < row;j++) printf("%4d",arr[i][j]); printf("\n"); } system("pause"); return 0; }