[LeetCode] 59. Spiral Matrix II

CodeAdventurerX
• 阅读 1440

Problem

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

Solution

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        if (n == 0) return res;
        int num = 1, rStart = 0, rEnd = n-1, cStart = 0, cEnd = n-1;
        while (rStart <= rEnd && cStart <= cEnd) {
            for (int j = cStart; j <= cEnd; j++) res[rStart][j] = num++;
            rStart++;
            for (int i = rStart; i <= rEnd; i++) res[i][cEnd] = num++;
            cEnd--;
            for (int j = cEnd; j >= cStart; j--) {
                if (rStart > rEnd) break;
                res[rEnd][j] = num++;
            }
            rEnd--;
            for (int i = rEnd; i >= rStart; i--) {
                if (cStart > cEnd) break;
                res[i][cStart] = num++;
            } 
            cStart++;
        }
        return res;
    }
}
点赞
收藏
评论区
推荐文章
blmius blmius
4年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
美凌格栋栋酱 美凌格栋栋酱
7个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
待兔 待兔
1年前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
码农印象 码农印象
4年前
【Typora】Typora 完全使用详解
<fontcolor"FF0000"Matrix精选</fontMatrix(https://sspai.com/matrix)是少数派的写作社区
Stella981 Stella981
3年前
PhoneGap设置Icon
参考:http://cordova.apache.org/docs/en/latest/config\_ref/images.html通过config.xml中的<icon标签来设置Icon<iconsrc"res/ios/icon.png"platform"ios"width"57"height"57"densi
可莉 可莉
3年前
18个常用 webpack插件,总会有适合你的!
!(https://oscimg.oschina.net/oscnet/71317da0c57a8e8cf5011c00e302a914609.jpg)来源| https://github.com/Michaellzg/myarticle/blob/master/webpack/Plugin何为插
Stella981 Stella981
3年前
Eigen库
MatrixXd表示任意size的矩阵,元素类型为double;VectorXd表示任意size的向量,元素类型为double.//创建31的向量v,并赋值为1,2,3VectorXdv(3);v<<1,2,3;使用固定尺寸的Matrix,Vector相比于可变尺寸的Matrix,Vector,例如Matri
Wesley13 Wesley13
3年前
MySQL总结(十一)子查询
!(https://oscimg.oschina.net/oscnet/upa344f41e81d3568e3310b5da00c57ced8ea.png)子查询1\.什么是子查询需求:查询开发部中有哪些员工selectfromemp;通
Stella981 Stella981
3年前
Nepxion Matrix
NepxionMatrix基于SpringRegistrar的代理机制前言NepxionMatrix是一款集成SpringAutoProxy,SpringRegistrar和SpringImportSelector三种机制的AOP框架,具有很
Stella981 Stella981
3年前
Leetcode 363.矩形区域不超过k的最大数值和
矩形区域不超过k的最大数值和给定一个非空二维矩阵 _matrix_和一个整数_k_,找到这个矩阵内部不大于_k_的最大矩形和。示例:输入:matrix\\1,0,1\,\0,2,3\\,k2输出:2解释: 矩形区域 \\0,1\,