顺时针打印矩阵

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

例如:输入矩阵

{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 

代码如下:

 1 typedef int (*Mystype)[4];//定义一个指向有4个int型数值的数组的指针,用来传递二维数组。这里的4是你输入矩阵的列数。
 2 
 3 void PrintMatrixCir(Mystype numbers ,int columns , int rows , int start);
 4 void PrintMatrixClockwisely(Mystype numbers ,int columns , int rows)
 5 {
 6     if (numbers == NULL || columns <= 0 || rows <= 0)
 7     {
 8         return;
 9     }
10     int start = 0 ;//start表示圈数
11     while (columns > start*2 && rows > start*2)// 满足条件就输出一圈
12     {
13         PrintMatrixCir(numbers ,columns ,rows , start);
14         start++;
15     }
16 
17 }
18 void PrintMatrixCir(Mystype numbers ,int columns , int rows , int start)
19 {
20     if (numbers == NULL || columns <= 0 || rows <= 0 || start < 0)
21     {
22         return;
23     }
24     int endX = columns - 1 - start ;
25     int endY = rows - 1 - start ;
26     if (start <= endX)//第一步,从左向右输出一行
27     {
28         for (int i = start ; i<= endX ;i++)
29         {
30             cout<<numbers[start][i]<<" ";
31         }
32     }
33     if (start < endY)//第二步,从上向下输出一列
34     {
35         for (int i = start + 1 ;i <= endY ; i++)
36         {
37             cout<<numbers[i][endX]<<" ";
38         }
39     }
40     if (start < endX && start <endY)//第三步,从右向左输出一行
41     {
42         for (int i = endX-1 ; i>=start ;i--)
43         {
44             cout<<numbers[endY][i]<<" ";
45         }
46     }
47     if (start < endX && start <endY-1)//第四步,从下向上输出一列
48     {
49         for (int i= endY - 1 ; i>= start+1 ; i--)
50         {
51             cout<<numbers[i][start]<<" ";
52         }
53     }
54 
55 }
56 
57 int main()
58 {
59     int numbers[4][4] = {
60         {1,    2,   3,   4 }, 
61         {5,    6,   7,   8 }, 
62         {9,   10,  11,  12 },
63         {13,  14,  15,  16 }
64     } ;
65     
66     Mystype p = numbers;
67     PrintMatrixClockwisely( p ,4 , 4 );
68     system("pause");
69     return 0;
70 }
原文地址:https://www.cnblogs.com/csxcode/p/3700331.html