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

时间:2024-05-06 22:05:43

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< || x>=matrix.size() || y< || y>=matrix[].size() || vis[x][y]) return false;
return true;
}
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res; res.clear();
if(matrix.size() == ) return res; vector<vector<bool> > vis(matrix.size(), vector<bool>(matrix[].size(), false)); int dir[][] = {{,}, {,}, {,-}, {-,}};
int __dir = , sx = , sy = , tot = matrix.size() * matrix[].size(), cnt = ;
while(cnt <= tot) {
res.push_back(matrix[sx][sy]);
vis[sx][sy] = true;
++cnt;
if(!check(matrix, vis, sx+dir[__dir][], sy+dir[__dir][])) __dir = (__dir+)%;
sx = sx + dir[__dir][];
sy = sy + dir[__dir][];
} return res;
}
};

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< || x>=n || y< || y>=n || vis[x][y]) return false;
return true;
}
vector<vector<int>> generateMatrix(int n) {
vector<vector<int> > res; res.resize();
if(n == ) return res; res.resize(n);
for(int i=;i<res.size();++i) res[i].resize(n);
vector<vector<bool> > vis(n, vector<bool>(n, false)); int dir[][] = {{,}, {,}, {,-}, {-,}};
int sx = , sy = , __dir = , tot = n * n, cnt = ; while(cnt <= tot) {
res[sx][sy] = cnt;
vis[sx][sy] = true;
++cnt;
if(!check(n, vis, sx + dir[__dir][], sy + dir[__dir][])) __dir = (__dir + ) % ;
sx = sx + dir[__dir][];
sy = sy + dir[__dir][];
} return res;
}
};