LeetCode.59 螺旋矩阵 II

这是一个关于LeetCode中螺旋矩阵II问题的解决方案。代码采用while循环,通过定义四个变量来跟踪矩阵的边界,然后按照右、下、左、上的顺序填充数值。循环结束后更新边界,直至完成矩阵填充。该算法实现了一个生成指定大小螺旋矩阵的功能。

原题

https://leetcode-cn.com/problems/spiral-matrix-ii/
在这里插入图片描述

思路

while循环,定义4个变量
最左列:left
最右列:right
最上行:top
最下行:bottom
每次循环 ➡️ ⬇️ ⬅️ ⬆️
循环完 left++ right-- top++ bottom–

题解

package com.leetcode.code;

/**
 * @ClassName Code59
 * @Author ZK
 * @Description
 * @Date 2021/2/4 10:18
 * @Version 1.0
 **/
public class Code59 {

    public static void main(String[] args) {
        int[][] res = generateMatrix(3);
        for (int i = 0; i < res.length; i++) {
            for (int j = 0; j < res[i].length; j++) {
                System.out.print(res[i][j] + "\t");
            }
            System.out.println();
        }
    }

    public static int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int count = 1;

        int left = 0;
        int right = n-1;
        int top = 0;
        int bottom = n-1;

        while(left <= right && top <= bottom){
//            右
            for (int i = left; i <= right; i++) {
                res[top][i] = count++;
            }

//            下
            for (int i = top+1; i <= bottom; i++) {
                res[i][right] = count++;
            }

//            左
            for (int i = right-1; i >= left; i--) {
                res[bottom][i] = count++;
            }
//            上
            for (int i = bottom-1; i >= top+1; i--) {
                res[i][left] = count++;
            }

            left++;
            right--;
            top++;
            bottom--;
        }

        return res;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

难过的风景

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值