首页 > 代码库 > 顺时针(逆时针)打印矩阵

顺时针(逆时针)打印矩阵

题目描述:顺时针打印一个任意arr[line][row]矩阵,如:

arr[5][4] 
1234
1415165
1320176
1219187
111098
arr[5][5]
116151413
217242312
318252211
419202110
56789

 

 

 

 

 

 

思路:顺时针打印  第一圈

先向右打印 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;
}

技术分享

 

顺时针(逆时针)打印矩阵