59 Spiral Matrix II (Analog)

1. Problem description:

Given a positive integer n, generate a square matrix containing all the elements from 1 to n2, and the elements are spirally arranged in a clockwise order.

Example:

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

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

2. Thinking analysis:

① In fact, the topic is relatively easy to understand. We can simulate the generation process of the entire array element according to our usual thinking. We can know that it was generated to the right at the beginning, the second is to generate elements below, and the third Generate elements on the left, and the fourth is to generate elements upwards, so you can use four while loops to generate an edge corresponding to a box. You can find that the condition that can generate the current array element is that the current element is zero, indicating that there is no previous It is filled and the current position does not exceed the boundary of the array, so the condition of the four while loops is that the current position does not exceed the array boundary and the current array element is zero. After filling a box, then the same is true for the second filling, so in The outermost layer can be set with a while loop. When the number of elements has not been generated, the outermost loop can be executed. When the loop is over, all the elements have been generated.

② The whole process is relatively easy to understand. Judging the boundary and the corresponding conditions can be completed. The overall code is not difficult. I also wrote my own solution in the collar button

3. The code is as follows

import java.util.Scanner;
public class Solution {
    public int[][] generateMatrix(int n) {
        if (n == 0) return null;
        int arr[][] = new int[n][n];
        int count = 2;
        int x = 0, y = 0;
        arr[0][0] = 1;
        while (count <= n * n){
            while (y + 1 < n && arr[x][y + 1] == 0){
                arr[x][y + 1] = count++;
                ++y;
            }
            while (x + 1 < n && arr[x + 1][y] == 0){
                arr[x + 1][y] = count++;
                ++x;
            }
            while (y - 1 >= 0 && arr[x][y - 1] == 0){
                arr[x][y - 1] = count++;
                --y;
            }
            while (x - 1 >= 0 && arr[x - 1][y] == 0){
                arr[x - 1][y] = count++;
                --x;
            }
        }
        return arr;
    }
}

 

Published 569 original articles · Like 153 · Visits 590,000+

Guess you like

Origin blog.csdn.net/qq_39445165/article/details/105313837