首页 > 代码库 > Spiral Matrix II

Spiral Matrix II

问题:蛇形矩阵
分析:设置变量dir,0123分别代表方向右下左上

class Solution {public:    int num[300][300];    void dfs(int x,int y,int k,int n,int dir)    {        num[x][y]=k;        if(k>=n*n) return ;//这里要用大于,n=0会一直不出现等于        if(dir==0)         {            if(y+1<n && num[x][y+1]==0 ) dfs(x,y+1,k+1,n,0);            else dfs(x+1,y,k+1,n,1);//如果右边不能走,就走下边        }        if(dir==1)        {            if( x+1<n && num[x+1][y]==0) dfs(x+1,y,k+1,n,1);            else dfs(x,y-1,k+1,n,2);        }        if(dir==2)        {            if(y-1>=0 && num[x][y-1]==0) dfs(x,y-1,k+1,n,2);            else dfs(x-1,y,k+1,n,3);        }        if(dir==3)        {            if(x-1>=0 && num[x-1][y]==0) dfs(x-1,y,k+1,n,3);            else dfs(x,y+1,k+1,n,0);        }    }    vector<vector<int> > generateMatrix(int n) {       // memset(num,0,sizeof(num));        vector<vector<int> >vec1;       dfs(0,0,1,n,0);        for(int i=0;i<n;i++)        {            vector<int> vec2;            for(int j=0;j<n;j++)            {                vec2.push_back(num[i][j]);            }            vec1.push_back(vec2);        }        return vec1;    }};