通常當我們遇到一個複雜的問題的時候,我們可以用圖形幫助我們思考。由於我們是以從外圈到內圈的順序依次打印,我們在矩陣中標註一圈作爲我們分析的目標。在下圖中,我們設矩陣的寬度爲columns,而其高度爲rows。我們我們選取左上角座標爲(startX, startY)。我們可以想象有一個循環,在每一次循環裏我們從(startX, startY)出發按照順時針打印數字。
接着我們分析這個循環結束的條件。對一個5×5的矩陣而言,最後一圈只有一個數字,對應的座標爲(2, 2)。我們發現5 > 2 * 2。對一個6×6的矩陣而言,最後一圈有四個數字,對應的座標仍然爲(2, 2)。我們發現6 > 2 * 2依然成立。於是我們可以得出,讓循環繼續的條件是columns > startX * 2 && rows > startY * 2。有了這些分析,我們就可以寫出如下的代碼:
#include <iostream>
using namespace std;
void Print(int num[][4], int rows, int cols, int start)
{
int i;
//shang
for(i=start; i<cols-start; i++)
cout<<num[start][i]<<endl;
//you
for(i=start+1; i<rows-start; i++)
cout<<num[i][cols - start-1]<<endl;
//xia
for(i=cols-start-2; i>=start; i--)
cout<<num[rows-start-1][i]<<endl;
//zuo
for(i=rows-start-2; i>start; i--)
cout<<num[i][start]<<endl;
}
void PrintMatrix(int num[][4], int rows, int cols)
{
if(num==NULL || rows<=0 || cols<=0)
return;
int start = 0;
while(rows > start*2 && cols > start*2)
{
Print(num, rows, cols, start);
start++;
}
}
int main()
{
int in[][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
PrintMatrix(in, 4, 4);
return 0;
}