首页 > 代码库 > Leetcode Spiral Matrix

Leetcode 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].

 螺旋数组, 从左到右,从上到下,四个方向构建循环

循环的时候注意边界的处理

class Solution {public:    vector<int> spiralOrder(vector<vector<int> > &matrix) {        vector<int> res;        if(matrix.empty()) return res;        int dx[] = {0,1,0,-1};        int dy[] = {1,0,-1,0};        int startx = 0,endx = matrix.size(), starty = 0,endy = matrix[0].size();        int cnt = endx*endy, direction = 0, x =0 , y = 0;        while(cnt > 0){            res.push_back(matrix[x][y]);            matrix[x][y] = -1;            cnt--;            int newx = x+dx[direction], newy=y+dy[direction];            if(newx >=endx ||newx<startx || newy>=endy|| newy < starty) {                direction++;                if(direction%4 == 1) startx++;                else if(direction%4 == 2) endy--;                else if(direction%4 == 3) endx--;                else starty ++;            }            direction%=4;            x+=dx[direction];y+=dy[direction];        }        return res;    }};