题目链接:https://leetcode.com/problems/spiral-matrix/
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]
.
思路:设置两个表示行进方向的向量flagX,flagY,还有边界值,然后在其到达边界的时候改变向量的值。每次位置累加为( x+flagX, y+flagY)。
大学的时候碰到过这个题,感觉挺麻烦的,现在做了感觉还是挺简单的。
代码如下:
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { if(matrix.size() == 0) return result; int flagX = 1, flagY = 0, i =0, x = 0, y =0; int left = 0, right = matrix[0].size()-1, top = 0, bottom = matrix.size()-1; int cnt = matrix.size()* matrix[0].size(); while(i < cnt) { result.push_back(matrix[y][x]); if(x >= right && flagX == 1)//遇到右边界 { flagX = 0; flagY = 1; top++; } else if(y >= bottom && flagY == 1)//遇到下边界 { flagX = -1; flagY = 0; right--; } else if(x <= left && flagX == -1)//遇到左边界 { flagX = 0; flagY = -1; bottom--; } else if(y <= top && flagY == -1)//遇到上边界 { flagX = 1; flagY = 0; left++; } x += flagX; y += flagY; i++; } return result; } private: vector<int> result; };