题目:输入一个矩阵,按照从外向里以顺时针一次打印出每个数字。例如 输入:ios
1 2 3 4spa
5 6 7 8code
9 10 11 12对象
13 14 15 16 则打印的顺序为:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16io
当遇到一个复杂问题的时候,能够使用图形来帮助咱们思考,因为是以从外圈到内圈的顺序依次打印,咱们能够把矩阵想象成若干的圈,以下图所示。能够使用一个循环来打印矩阵,每一次打印矩阵中的一个圈。class
把矩阵当作是由若干个顺时针的圈组成。接下来分析循环的结束条件。假设矩阵的行数是 rows,列数是 columns。打印第一圈的左上角的坐标是(0,0),第二圈的左上角的坐标是(1, 1),以此类推。左上角的坐标中行标和列标都是相同的,能够在矩阵中选取左上角的元素做为分析的对象。能够得出,循环继续的条件是 columns > startX * 2 而且 rows > startY * 2. 能够使用以下循环来打印矩阵;stream
void PrintMatrixClockwisely(int numbers[][MaxSize], int columns, int rows)
{
if(numbers == NULL || columns == 0 || rows == 0)
return;
int start = 0;
while(columns > 2 * start && rows > 2 * start)
{
PrintMatrixInCircle(numbers, columns, rows, start);
++start;
}
}循环
接下来考虑打印一圈的功能,能够将打印一圈分为四步:1)从左到右打印一行 2)从上到下打印一列 3)从右到左打印一行 4)从下到上打印一列。im
不过值得注意的是,最后一圈可能退化成只有一行,只有一列,甚至只有一个数字,所以打印这样的一圈就再也不须要四步。以下图:img
所以,打印时每一步的前提条件:第一步老是须要的,由于打印一圈至少有一步。若是只有一行,那么就不用第二步了。也就是须要第二步的前提条件是终止行号大于起始行号。须要第三步打印的前提条件是圈内至少有两行两列,也就是说除了要求终止行号大于起始行号以外,还要求终止列号大于起始列号。同理,须要打印的第四步的前提条件是至少有三行两列,所以,要求终止行号比起始行号至少大2,同时,终止列号大于起始列号。
void PrintMatrixInCircle(int numbers[][MaxSize], int columns, int rows, int start)
{
int endX = columns - start - 1;
int endY = rows - start -1;
//从左往右打印上面一行
for(int i = start; i <= endX; ++i)
{
int number = numbers[start][i];
cout << number <<" ";
}
//从上往下打印外侧一列
if(start < endY)
{
for(int i = start + 1; i <= endY; ++i)
{
int number = numbers[i][endX];
cout << number << " ";
}
}
//从右往左打印下面一行
if(start < endX && start < endY)
{
for(int i = endX - 1; i >= start; --i)
{
int number = numbers[endY][i];
cout << number << " ";
}
}
//从下往上打印内侧一列
if(start < endX && start < endY - 1)
{
for(int i = endY - 1; i >= start + 1; --i)
{
int number = numbers[i][start];
cout << number << " ";
}
}
}
//顺时针打印矩阵 #include<iostream> using namespace std; const int MaxSize = 4; //打印矩阵里的一圈 void PrintMatrixInCircle(int numbers[][MaxSize], int columns, int rows, int start) { int endX = columns - start - 1; int endY = rows - start -1; //从左往右打印上面一行 for(int i = start; i <= endX; ++i) { int number = numbers[start][i]; cout << number <<" "; } //从上往下打印外侧一列 if(start < endY) { for(int i = start + 1; i <= endY; ++i) { int number = numbers[i][endX]; cout << number << " "; } } //从右往左打印下面一行 if(start < endX && start < endY) { for(int i = endX - 1; i >= start; --i) { int number = numbers[endY][i]; cout << number << " "; } } //从下往上打印内侧一列 if(start < endX && start < endY - 1) { for(int i = endY - 1; i >= start + 1; --i) { int number = numbers[i][start]; cout << number << " "; } } } void PrintMatrixClockwisely(int numbers[][MaxSize], int columns, int rows) { if(numbers == NULL || columns == 0 || rows == 0) return; int start = 0; while(columns > 2 * start && rows > 2 * start) { PrintMatrixInCircle(numbers, columns, rows, start); ++start; } } int main() { int num[5][4] = {{1, 2, 3, 4},{5, 6, 7, 8},{9, 10, 11, 12}, {13, 14, 15, 16},{17, 18, 19, 20}}; PrintMatrixClockwisely(num, 4, 5); system("pause"); return 0; }