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;
    }
}
相关推荐
呱牛do it3 小时前
企业级门户网站设计与实现:基于SpringBoot + Vue3的全栈解决方案(Day 3)
java·vue
神の愛4 小时前
左连接查询数据 left join
java·服务器·前端
南境十里·墨染春水4 小时前
linux学习进展 线程同步——互斥锁
java·linux·学习
雨奔5 小时前
Kubernetes 联邦 Deployment 指南:跨集群统一管理 Pod
java·容器·kubernetes
杨凯凡5 小时前
【021】反射与注解:Spring 里背后的影子
java·后端·spring
lulu12165440785 小时前
Claude Code项目大了响应慢怎么办?Subagents、Agent Teams、Git Worktree、工作流编排四种方案深度解析
java·人工智能·python·ai编程
riNt PTIP5 小时前
SpringBoot创建动态定时任务的几种方式
java·spring boot·spring
小辉同志5 小时前
215. 数组中的第K个最大元素
数据结构·算法·leetcode··快速选择
老星*5 小时前
AI选股核心设计思路
java·ai·开源·软件开发
それども6 小时前
Comparator.comparing 和 拆箱问题
java·jvm