Java | Leetcode Java题解之第59题螺旋矩阵II

题目:

题解:

java 复制代码
class Solution {
    public int[][] generateMatrix(int n) {
        int num = 1;
        int[][] matrix = new int[n][n];
        int left = 0, right = n - 1, top = 0, bottom = n - 1;
        while (left <= right && top <= bottom) {
            for (int column = left; column <= right; column++) {
                matrix[top][column] = num;
                num++;
            }
            for (int row = top + 1; row <= bottom; row++) {
                matrix[row][right] = num;
                num++;
            }
            if (left < right && top < bottom) {
                for (int column = right - 1; column > left; column--) {
                    matrix[bottom][column] = num;
                    num++;
                }
                for (int row = bottom; row > top; row--) {
                    matrix[row][left] = num;
                    num++;
                }
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return matrix;
    }
}
相关推荐
laplace01237 分钟前
Maven
java·maven
wdfk_prog8 分钟前
Xshell终端连接Ubuntu/Debian无颜色的解决方案
java·ubuntu·debian
艾迪的技术之路25 分钟前
linux上gitlab runner部署文档
java·github
凌波粒28 分钟前
SpringMVC基础教程(3)--SSM框架整合
java·sql·spring·intellij-idea·mybatis
2021_fc44 分钟前
分布式应用可观测全链路追踪技术
java
数据的世界011 小时前
JAVA和C#的语法对比
java·windows·c#
渡我白衣1 小时前
深入理解 OverlayFS:用分层的方式重新组织 Linux 文件系统
android·java·linux·运维·服务器·开发语言·人工智能
百***92651 小时前
java进阶1——JVM
java·开发语言·jvm
虫师c1 小时前
字节码(Bytecode)深度解析:跨平台运行的魔法基石
java·jvm·java虚拟机·跨平台·字节码
q***72191 小时前
Spring Boot环境配置
java·spring boot·后端