1 #include "000库函数.h" 2 3 4 //我们定义p,q为当前环的高度和宽度,当p或者q为1时, 5 //表示最后一个环只有一行或者一列,可以跳出循环。 6 //此题的难点在于下标的转换,如何正确的转换下标是解此题的关键, 7 //我们可以对照着上面的3x3的例子来完成下标的填写,代码如下: 8 class Solution { 9 public: 10 vector<int> spiralOrder(vector<vector<int>>& matrix) { 11 vector<int>res; 12 if (matrix.empty() || matrix[0].empty())return res; 13 int m = matrix.size(), n = matrix[0].size(); 14 int c = m > n ? (n + 1) / 2 : (m + 1) / 2; 15 int p = m, q = n; 16 for (int i = 0; i < c; ++i, p -= 2, q -= 2) { 17 for (int col = i; col < i + q; ++col)//向右扫行 18 res.push_back(matrix[i][col]); 19 for (int row = i + 1; row < i + p; ++row)//向下扫列 20 res.push_back(matrix[row][i + q - 1]); 21 if (p == 1 || q == 1)break; 22 for (int col = i + q - 2; col >= i; --col)//向左扫行 23 res.push_back(matrix[i + p - 1][col]); 24 for (int row = i + p - 2; row > i; --row)//向上扫列 25 res.push_back(matrix[row][i]); 26 } 27 return res; 28 } 29 }; 30 31 //对于这种螺旋遍历的方法,重要的是要确定上下左右四条边的位置, 32 //那么初始化的时候,上边up就是0,下边down就是m - 1,左边left是0,右边right是n - 1。 33 //然后我们进行while循环,先遍历上边,将所有元素加入结果res,然后上边下移一位, 34 //如果此时上边大于下边,说明此时已经遍历完成了,直接break。同理对于下边,左边,右边, 35 //依次进行相对应的操作,这样就会使得坐标很有规律,并且不易出错,参见代码如下: 36 37 class Solution { 38 public: 39 vector<int> spiralOrder(vector<vector<int>>& matrix) { 40 vector<int>res; 41 if (matrix.empty() || matrix[1].empty())return res; 42 int m = matrix.size(), n = matrix[0].size(); 43 int up = 0, down = m - 1, left = 0, right = n - 1; 44 while (1) { 45 for (int j = left; j <= right; ++j)res.push_back(matrix[up][j]); 46 if (++up > down)break; 47 for (int i = up; i <= down; ++i)res.push_back(matrix[i][right]); 48 if (--right < left)break; 49 for (int j = right; j >= left; --j)res.push_back(matrix[down][j]); 50 if (--down < up)break; 51 for (int i = down; i >= up; --i)res.push_back(matrix[i][left]); 52 if (++left > right)break; 53 } 54 return res; 55 } 56 }; 57 58 59 60 void T054() { 61 Solution s; 62 vector<int>v; 63 vector<vector<int>>m; 64 m = { {1,2,3},{4,5,6},{7,8,9} }; 65 v = s.spiralOrder(m); 66 for (auto a : v) 67 cout << a << " "; 68 cout << endl; 69 m = { {1} }; 70 v = s.spiralOrder(m); 71 for (auto a : v) 72 cout << a << " "; 73 cout << endl; 74 75 }