【Leetcode】59. 螺旋矩阵 II

246 阅读1分钟

题目描述

在这里插入图片描述

给你一个正整数 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++;
            }
        }
    }
}