首页 > 代码库 > 顺时针(逆时针)打印矩阵
顺时针(逆时针)打印矩阵
题目描述:顺时针打印一个任意arr[line][row]矩阵,如:
1 | 2 | 3 | 4 |
14 | 15 | 16 | 5 |
13 | 20 | 17 | 6 |
12 | 19 | 18 | 7 |
11 | 10 | 9 | 8 |
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 |
思路:顺时针打印 第一圈
先向右打印 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;
}
逆时针:
#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;
}
顺时针(逆时针)打印矩阵