leetcode 59. Spiral Matrix II-螺旋矩阵|清晰思路

本文介绍了一种生成螺旋矩阵的方法,并提供了Java与Python两种语言的实现。通过定义x、y坐标及移动步数等变量,实现了从外向内螺旋填充数字的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接:59. Spiral Matrix II

【思路】


遍历图解如上图所示,n 分为偶数和奇数两种情况。当 n 为偶数时,最后一次遍历刚好添加完毕;当 n 为奇数时,最后还需要进行一次添加操作⑤。另外,注意我所定义的 x 方向是竖向,y 方向是横向的。

public class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int num=1, d=n-1, x=(n-d)/2, y=(n-d)/2;
        while (d > 0) {
            for(int i=0; i<d; i++) res[x][y+i] = num++;  //①
            y += d;
            for(int i=0; i<d; i++) res[x+i][y] = num++;  //②
            x += d;
            for(int i=0; i<d; i++) res[x][y-i] = num++;  //③
            y = (n-d) / 2;
            for(int i=0; i<d; i++) res[x-i][y] = num++;  //④
            d -= 2;
            x = (n-d) / 2;
            y = (n-d) / 2;
        }
        if (d==0) res[x][y] = num;  //⑤
        return res;
    }
}
21 / 21  test cases passed. Runtime: 0 ms  Your runtime beats 20.33% of javasubmissions.


Python 在语法上做了小小的优化,将4个循环合并:

class Solution(object):
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        res, step, x, y, num = [[0]*n for i in range(n)], n-1, 0, 0, 1
        dx, dy = [0,1,0,-1], [1,0,-1,0]
        while step > 0 :
            for i in range(4) :
                for j in range(step) :
                    res[x][y] = num
                    x, y, num = x+dx[i], y+dy[i], num+1
            step -= 2
            x,y = (n-step)/2, (n-step)/2
        if step == 0 : res[x][y] = num
        return res
21 / 21  test cases passed. Runtime: 60 ms  Your runtime beats 22.66% of pythonsubmissions.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值