顺时针打印二维数组,以前在牛客网上做过,不过还是忘了
int n,m;
vector<vector<bool> > v;
bool judge(int i,int j)
{
return i>=0 && i<n && j>=0 && j<m && !v[i][j]; //判断,相当于小旗子 右,下,左,上
}
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> res;
if( !(n = matrix.size()) || !(m = matrix[0].size()))
return res;
v = vector<vector<bool> >(n,vector<bool>(m,false)); //如何定义二维数组!
const int D[4][2] = {{0,1},{1,0},{0,-1},{-1,0}}; //四个方向
int i = 0, j = 0, d = 0, T = m * n;
while(T--){
res.push_back(matrix[i][j]);
v[i][j] = true;
if(!judge(i + D[d][0], j + D[d][1])) (++d) %= 4; //转弯
i += D[d][0], j += D[d][1];//前进
}
return res;
}
Spiral Matrix II
class Solution {
vector<vector<bool>> v;
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res=vector<vector<int> >(n,vector<int>(n));
v=vector<vector<bool>>(n,vector<bool>(n,false));
int num=n*n;
if(num == 0)
return res;
int i=0;
int row=0,col=0;
int D[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int d=0;
while(++i<=num)
{
res[row][col]=i;
v[row][col]=true;
if(!judge(n,row+D[d][0],col+D[d][1])) //if(row<0 || row>=n || col<0 || col>=n || v[row][col]) 这么写为什么不对
(++d) %= 4;
row +=D[d][0],col+=D[d][1];
}
return res;
}
bool judge(int n,int row,int col)
{
return row>=0 && row<n && col>=0 && col<n && !v[row][col];
}
};
浙公网安备 33010602011771号