題目描述
輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每一個數字,例如,如果輸入如下4 X 4矩陣: 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.
模擬過程,注意細節
class Solution
{
public:
vector<int> printMatrix(vector<vector<int>> matrix)
{
int row1 = 0, row2 = matrix.size() - 1;
if (matrix.size() == 0)
return {};
int col1 = 0, col2 = matrix[0].size() - 1;
vector<int> ans;
//0正序 往左或者往下
int cntRow = 0;
int cntCol = 0;
//0水平方向輸出
int turn = 0;
while (row1 <= row2 && col1 <= col2)
{
if (turn == 0)
{
turn = 1;
if (cntRow == 0)
{
cntRow = 1;
for (int i = col1; i <= col2; ++i)
ans.push_back(matrix[row1][i]);
++row1;
}
else
{
cntRow = 0;
for (int i = col2; i >= col1; --i)
ans.push_back(matrix[row2][i]);
--row2;
}
}
else
{
turn = 0;
if (cntCol == 0)
{
cntCol = 1;
for (int i = row1; i <= row2; ++i)
ans.push_back(matrix[i][col2]);
--col2;
}
else
{
cntCol = 0;
for (int i = row2; i >= row1; --i)
ans.push_back(matrix[i][col1]);
++col1;
}
}
}
return ans;
}
};