Print the matrix clockwise (counterclockwise) and counter-clockwise.
Description: print an arbitrary arr [line] [row] matrix clockwise, for example:
Arr [5] [4]
1 |
2 |
3 |
4 |
14 |
15 |
16 |
5 |
13 |
20 |
17 |
6 |
12 |
19 |
18 |
7 |
11 |
10 |
9 |
8 |
Arr [5] [5]
1 |
16 |
15 |
14 |
13 |
2 |
17 |
24 |
23 |
12 |
3 |
18 |
25 |
22 |
11 |
4 |
19 |
20 |
21 |
10 |
5 |
6 |
7 |
8 |
9 |
Idea: print the first circle clockwise
Print arr [0] [0] To the right ---> arr [0] [row-1]
Print arr [1] [row-1] ---> arr [line-1] [row-1]
Print arr [line-1] [row-2] To the left ---> arr [line-1] [0]
Finally, print arr [line-2] [0] ---> arr [1] [0]
Then, the nth circle starts from arr [n] [n] as the first element until it ends. The cnt count can be used as the exit condition because num <= line * row
When it is not a matrix of level m, there are n loops n = (line <row? Line: row)/2
Val reduces the cycle size by 2.
Note: Unlike starting coordinates
#include<stdio.h>#include<stdlib.h>#define line 5#define row 4int 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;}
Counterclockwise:
#include<stdio.h>#include<stdlib.h>#define line 5#define row 5int 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;}