螺旋矩阵 II(模拟)

58 阅读1分钟

 我寻思着这不就是蛇形填数吗

直接上代码

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int> >ans(n,vector<int>(n,0));
        int x=0,y=0,total=1;
        ans[x][y]=1;
        vector<vector<int> >book(n,vector<int>(n,0));
        while(total<n*n)
        {
            while(y+1<n&&book[x][y+1]==0)
            {
                book[x][y]=1;
                ans[x][++y]=++total;
            }
            while(x+1<n&&book[x+1][y]==0)
            {
                book[x][y]=1;
                ans[++x][y]=++total;
            }
            while(y-1>=0&&book[x][y-1]==0)
            {
                book[x][y]=1;
                ans[x][--y]=++total;
            }
            while(x-1>=0&&book[x-1][y]==0)
            {
                book[x][y]=1;
                ans[--x][y]=++total;
            }
        }
        return ans;
    }
};

不过我在看题解的时候倒是看到了一个不错的题解,这里也分享给大家

class Solution {
public:
int nextt[4][2] = { {0,1},{1,0},{0,-1},{-1,0} };
vector<vector<int>> generateMatrix(int n) {
    int x = 0, y = 0, total = 0, i = 0;
    vector<vector<int> >ans(n, vector<int>(n, 0));
    vector<vector<int> >book(n, vector<int>(n, 0));
    while (total < n * n)//循环全部格子
    {
        book[x][y] = 1;//走过了
        ans[x][y] = ++total;填入数组
        int nextx = x + nextt[i][0];
        int nexty = y + nextt[i][1];计算下一步的下标
        if (nextx < 0 || nextx >= n || nexty < 0 || nexty >= n || book[nextx][nexty] == 1 || total >= n * n)//如果走到头了我们就拐弯(有点像DFS)
        {
            i = (i + 1) % 4;//顺时针转弯
        }
        x = x + nextt[i][0];
        y = y + nextt[i][1];
    }
    return ans;
}
int main()
{
    vector<vector<int> >ans;
    int n;
    cin >> n;
    ans = generateMatrix(n);
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            cout << ans[i][j] << ' ';
        }
        cout << endl;
    }
    return 0;
}

};