[LeetCode]59.螺旋矩阵II

本文详细介绍了如何实现一个生成螺旋矩阵的算法,通过一个二维数组和四个方向数组进行移动,同时避免了使用额外的visited数组。核心思路是利用边界判断和方向切换,实现了从1到n*n的螺旋填充。优化点在于通过检查res[nextI][nextJ]是否已填充,而不是使用visited数组。
class Solution {
    public int[][] generateMatrix(int n) {
        int end = n * n;
        int counter = 1;
        int[][] res = new int[n][n];
        boolean[][] visited = new boolean[n][n];
        int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int i = 0;
        int j = 0;
        int directionIndex = 0;
        while(counter <= end){
            res[i][j] = counter;
            visited[i][j] = true;
            counter ++;
            int nextI = i + directions[directionIndex][0];
            int nextJ = j + directions[directionIndex][1];
            if(nextI < 0 || nextI >= n || nextJ < 0 || nextJ >=n || visited[nextI][nextJ]){
                directionIndex = (directionIndex + 1) % 4;
            }
            i += directions[directionIndex][0];
            j += directions[directionIndex][1];

        }
        return res;
    }
}

本题的思路和螺旋矩阵类似,通过方向数组和边界判断实现螺旋转向。

另外,不需要使用 visited 函数确定是否访问过该点,而是直接根据 res[nextI][nextJ] > 0 来判断。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值