顺时针打印矩阵,比如:
1 2 3 4
14 15 16 5
13 20 17 6
12 19 18 7
11 10 9 8
打印结果为 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
将问题分解成每次打印一圈,打印 n 圈来解决
void printMatrix(vector<vector<int>> &nums, int columns, int rows)
{
if(rows <= 0 || columns <= 0)
return;
int start = 0;
while(columns > start * 2 && rows > start * 2)
{
printMatrixIncicle(nums, columns, rows, start);
++start;
}
}
void printMatrixIncicle(vector<vector<int>> &nums, int columns, int rows, int start)
{
int endX = columns - 1 -start;
int endY = rows - 1- start;
for(int i = start; i <= endX; ++i) //从左到右一行
cout << nums[start][i] << " ";
if(start < endY)
{
for(int i = start + 1; i <= endY; ++i) //从上到下一列
cout << nums[i][endX] << " ";
}
if(start < endX && start < endY)
{
for(int i = endX - 1; i >= start; --i) //从右到左一行
cout << nums[endY][i] << " ";
}
if(start < endX && start < endY - 1)
{
for(int i = endY - 1; i >= start; --i) //从下到上一列
cout << nums[i][start] << " ";
}
}