Leetcode59螺旋矩阵2

代码:

java 复制代码
class Solution {
    public int[][] generateMatrix(int n) {
        if(n==1){
            int[][] arr = {{1}};
            return arr; 
        }
        int[][] arr = new int[n][n];
        int cnt=1;
        int left = 0,right = n-1,top=0,down=n-1;
        while(left<right){
            for(int i=left;i<right;i++){
                arr[top][i] = cnt++;
            }
            for(int j=top;j<down;j++){
                arr[j][right] = cnt++;
            }
            for(int i=right;i>left;i--){
                arr[down][i] = cnt++;
            }
            for(int j=down;j>top;j--){
                arr[j][left] = cnt++;
            }
            left++;
            right--;
            top++;
            down--;
        }
        if(cnt==n*n){
            arr[left][top] = n*n;
        }
        return arr;
    }
}
相关推荐
.生产的驴16 分钟前
SpringBoot 封装统一API返回格式对象 标准化开发 请求封装 统一格式处理
java·数据库·spring boot·后端·spring·eclipse·maven
猿周LV23 分钟前
JMeter 安装及使用 [软件测试工具]
java·测试工具·jmeter·单元测试·压力测试
知来者逆25 分钟前
计算机视觉——速度与精度的完美结合的实时目标检测算法RF-DETR详解
图像处理·人工智能·深度学习·算法·目标检测·计算机视觉·rf-detr
晨集25 分钟前
Uni-App 多端电子合同开源项目介绍
java·spring boot·uni-app·电子合同
时间之城28 分钟前
笔记:记一次使用EasyExcel重写convertToExcelData方法无法读取@ExcelDictFormat注解的问题(已解决)
java·spring boot·笔记·spring·excel
阿让啊30 分钟前
C语言中操作字节的某一位
c语言·开发语言·数据结构·单片机·算法
এ᭄画画的北北30 分钟前
力扣-160.相交链表
算法·leetcode·链表
椰羊~王小美35 分钟前
LeetCode -- Flora -- edit 2025-04-25
java·开发语言
凯酱42 分钟前
MyBatis-Plus分页插件的使用
java·tomcat·mybatis
程序员总部1 小时前
如何在IDEA中高效使用Test注解进行单元测试?
java·单元测试·intellij-idea