【Leetcode】59. 螺旋矩阵 II

题目描述

在这里插入图片描述

给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。

题解

这道题不能说和【Leetcode】54. 螺旋矩阵非常相似,只能说是一模一样。

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户

内存消耗:36.3 MB, 在所有 Java 提交中击败了82.70%的用户

class Solution {
    int[][] res;
    int count = 1;
    
    public int[][] generateMatrix(int n) {
        this.res = new int[n][n];
        int row1 = 0;
        int row2 = n - 1;
        int col1 = 0;
        int col2 = n - 1;
        while (row1 <= row2 && col1 <= col2) {
            goRound(row1, row2, col1, col2);
            row1++;row2--;col1++;col2--;
        }
        return res;
    }
    
    public void goRound(int row1, int row2, int col1, int col2) {
        for (int i = col1; i <= col2; i++) {
            res[row1][i] = count++;
        }
        for (int i = row1 + 1; i <= row2; i++) {
            res[i][col2] = count++;
        }
        if (row1 != row2) {
            for (int i = col2 - 1; i >= col1; i--) {
                res[row2][i] = count++;
            }
        }
        if (col1 != col2) {
            for (int i = row2 - 1; i >= row1 + 1; i--) {
                res[i][col1] = count++;
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

锥栗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值