/*
思想,用左上和右下的座標定位出一次要旋轉打印的數據,一次旋轉打印結束後,往對角分別前進和後退一個單位。
提交代碼時,主要的問題出在沒有控制好後兩個for循環,需要加入條件判斷,防止出現單行或者單列的情況。
*/
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
int row = matrix.size();
int col = matrix[0].size();
vector<int> res;
// 輸入的二維數組非法,返回空的數組
if (row == 0 || col == 0) return res;
// 定義四個關鍵變量,表示左上和右下的打印範圍
int left = 0, top = 0, right = col - 1, bottom = row - 1;
while (left <= right && top <= bottom)
{
// left to right
for (int i = left; i <= right; ++i) res.push_back(matrix[top][i]);
// top to bottom
for (int i = top + 1; i <= bottom; ++i) res.push_back(matrix[i][right]);
// right to left
if (top != bottom)
for (int i = right - 1; i >= left; --i) res.push_back(matrix[bottom][i]);
// bottom to top
if (left != right)
for (int i = bottom - 1; i > top; --i) res.push_back(matrix[i][left]);
left++,top++,right--,bottom--;
}
return res;
}
};