题目:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
You should return [1,2,3,6,9,8,7,4,5]
. (Medium)
分析:
题目没有什么复杂的算法要应用,就是一行一列输出,处理好细节即可。
比较清晰的写法是搞一个rowBegin, rowEnd, colBegin, colEnd, 并在处理完一行/一列后更新值,并判断是否仍然满足 rowBegin <= rowEnd && colBegin <= colEnd
代码:
1 class Solution { 2 public: 3 vector<int> spiralOrder(vector<vector<int>>& matrix) { 4 vector<int> result; 5 if (matrix.size() == 0) { 6 return result; 7 } 8 int m = matrix.size(), n = matrix[0].size(); 9 int rowBegin = 0, rowEnd = m - 1, colBegin = 0, colEnd = n - 1; 10 while (rowBegin <= rowEnd && colBegin <= colEnd) { 11 for (int i = colBegin; i <= colEnd; ++i ) { 12 result.push_back(matrix[rowBegin][i]); 13 } 14 rowBegin++; 15 if (rowBegin > rowEnd) { 16 break; 17 } 18 for (int i = rowBegin; i <= rowEnd; ++i) { 19 result.push_back(matrix[i][colEnd]); 20 } 21 colEnd--; 22 if (colBegin > colEnd) { 23 break; 24 } 25 for (int i = colEnd; i >= colBegin; --i) { 26 result.push_back(matrix[rowEnd][i]); 27 } 28 rowEnd--; 29 if (rowBegin > rowEnd) { 30 break; 31 } 32 for (int i = rowEnd; i>= rowBegin; --i) { 33 result.push_back(matrix[i][colBegin]); 34 } 35 colBegin++; 36 } 37 return result; 38 } 39 };