leetcode@ [54/59] Spiral Matrix & Spiral Matrix II

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

class Solution {
public:
    bool check(vector<vector<int> >& matrix, vector<vector<bool> >& vis, int x, int y) {
        if(x<0 || x>=matrix.size() || y<0 || y>=matrix[0].size() || vis[x][y]) return false;
        return true;
    }
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> res; res.clear();
        if(matrix.size() == 0) return res;
        
        vector<vector<bool> > vis(matrix.size(), vector<bool>(matrix[0].size(), false)); 
        
        int dir[4][2] = {{0,1}, {1,0}, {0,-1}, {-1,0}};
        int __dir = 0, sx = 0, sy = 0, tot = matrix.size() * matrix[0].size(), cnt = 1;
        while(cnt <= tot) {
            res.push_back(matrix[sx][sy]);
            vis[sx][sy] = true;
            ++cnt;
            if(!check(matrix, vis, sx+dir[__dir][0], sy+dir[__dir][1]))  __dir = (__dir+1)%4;
            sx = sx + dir[__dir][0];
            sy = sy + dir[__dir][1];
        }
        
        return res;
    }
};
View Code

 

https://leetcode.com/problems/spiral-matrix-ii/

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:

 

[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

class Solution {
public:
    bool check(int n, vector<vector<bool> >& vis, int x, int y) {
        if(x<0 || x>=n || y<0 || y>=n || vis[x][y]) return false;
        return true;
    }
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int> > res; res.resize(0);
        if(n == 0) return res;
        
        res.resize(n);
        for(int i=0;i<res.size();++i) res[i].resize(n);
        vector<vector<bool> > vis(n, vector<bool>(n, false)); 
        
        int dir[4][2] = {{0,1}, {1,0}, {0,-1}, {-1,0}};
        int sx = 0, sy = 0, __dir = 0, tot = n * n, cnt = 1;
        
        while(cnt <= tot) {
            res[sx][sy] = cnt;
            vis[sx][sy] = true;
            ++cnt;
            if(!check(n, vis, sx + dir[__dir][0], sy + dir[__dir][1])) __dir = (__dir + 1) % 4;
            sx = sx + dir[__dir][0];
            sy = sy + dir[__dir][1];
        }
        
        return res;
    }
};
View Code

 

 



posted @ 2015-11-17 12:48  流白  阅读(199)  评论(0编辑  收藏  举报