【LeetCode】 59.螺旋矩阵 II (spiral Matrix II)

505 阅读1分钟

题目描述

英文版描述

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n(2) in spiral order.

Example 1:

Input: n = 3

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

Example 2:

Input: n = 1

Output: [[1]]

提示:

  • 1 <= n <= 20

英文版地址

leetcode.com/problems/sp…

中文版描述

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

示例 1:

输入: n = 3

输出: [[1,2,3],[8,9,4],[7,6,5]]

示例 2:

输入: n = 1

输出: [[1]]

提示:

  • 1 <= n <= 20

中文版地址

leetcode.cn/problems/sp…

俺这版

class Solution {
    public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
        int row; // 行
        int col; // 列
        // 起始点
        int start = 0;
        // 初始值
        int num = 1;
        // 循环次数
        int loop = 1;

        while (start <= (n - 1) / 2 + 1) {
            for (int i = start; i < (n - loop); i++) {
                row = start;
                col = i;
                result[row][col] = num;
                num++;
            }
            for (int i = start; i < (n - loop); i++) {
                row = i;
                col = (n - loop);
                result[row][col] = num;
                num++;
            }
            for (int i = (n - loop); i > start; i--) {
                row = (n - loop);
                col = i;
                result[row][col] = num;
                num++;
            }
            for (int i = (n - loop); i > start; i--) {
                row = i;
                col = start;
                result[row][col] = num;
                num++;
            }
            start++;
            loop++;
        }

        if (n % 2 == 1) {
            result[n/2][n/2] = num;
        }
        return result;
    }
}

复杂度分析

  • 时间复杂度:O(n^2)
  • 空间复杂度:O(1)