您的位置:首页 > 其它

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

2015-11-17 12:48 405 查看
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(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

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: