leetcode 59.螺旋矩阵II Java

螺旋矩阵II

  • 做题博客链接
  • 题目链接
  • 描述
  • 示例
  • 初始代码模板
  • 代码

做题博客链接

https://blog.csdn.net/qq_43349112/article/details/108542248

题目链接

https://leetcode-cn.com/problems/spiral-matrix-ii/

描述

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

提示:

1 <= n <= 20

示例

示例 1:
在这里插入图片描述

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

示例 2:

输入:n = 1
输出:[[1]]

初始代码模板

class Solution {
    public int[][] generateMatrix(int n) {
    
    }
}

代码

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] arr = new int[n][n];
        int count = 1;

        int left = 0;
        int right = n - 1;
        int top = 0;
        int down = n - 1;

        int finalVal = n * n;
        while (count <= finalVal) {
            for (int i = left; i <= right && count <= finalVal; i++) {
                arr[top][i] = count++;
            }
            top++;

            for (int i = top; i <= down && count <= finalVal; i++) {
                arr[i][right] = count++;
            }
            right--;

            for (int i = right; i >= left && count <= finalVal; i--) {
                arr[down][i] = count++;
            }
            down--;

            for (int i = down; i >= top && count <= finalVal; i--) {
                arr[i][left] = count++;
            }
            left++;
        }

        return arr;
    }
}

你可能感兴趣的:(leetcode刷题,算法,java,leetcode)