Leetcode Spiral Matrix

OpenSoucre發表於2014-06-29

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;
    }
};

 

相關文章