Leetcode#54 Spiral Matrix
简单模拟,用t,b,l,r分别表示当前的上下左右四个边界,然后遍历即可
代码:
1 vector<int> spiralOrder(vector<vector<int> > &matrix) { 2 if (matrix.empty() || matrix[0].empty()) return vector<int>(); 3 4 vector<int> path; 5 int m = matrix.size(); 6 int n = matrix[0].size(); 7 int t = 0; 8 int b = m - 1; 9 int l = 0; 10 int r = n - 1; 11 int i = 0; 12 int j = 0; 13 14 while (t <= b && l <= r) { 15 while (t <= b && l <= r && j <= r) path.push_back(matrix[i][j++]); 16 i++; 17 j--; 18 t++; 19 while (t <= b && l <= r && i <= b) path.push_back(matrix[i++][j]); 20 i--; 21 j--; 22 r--; 23 while (t <= b && l <= r && j >= l) path.push_back(matrix[i][j--]); 24 i--; 25 j++; 26 b--; 27 while (t <= b && l <= r && i >= t) path.push_back(matrix[i--][j]); 28 i++; 29 j++; 30 l++; 31 } 32 33 return path; 34 }