Leetcode(Java)-59. 螺旋矩阵 II

给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3
输出:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

class Solution {
    public int[][] generateMatrix(int n) {
        boolean[][] visited = new boolean[n+2][n+2];
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=n;j++)
            {
                visited[i][j] = true;
            }
        }
        int[] dx = {0,1,0,-1};
        int[] dy = {1,0,-1,0};
        int[][] res =new int[n][n];
        int index=1;
        int x=1;
        int y=1;
        while(index<=n*n)
        {
            for(int i=0;i<4;i++)
            {
                if(index == n*n) {
                    res[x-1][y-1] = index;
                    return res;
                }
                while(visited[x+dx[i]][y+dy[i]])
                {
                    res[x-1][y-1] = index++;
                    visited[x][y] = false;
                    x=x+dx[i];
                    y=y+dy[i];
                }
            }
        }
        return res;
    }
}
发布了241 篇原创文章 · 获赞 34 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_38905818/article/details/104296487