LeetCode 0059. Spiral Matrix II Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0059. Spiral Matrix II

Description

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 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]]

 

Constraints:

  • 1 <= n <= 20

Solutions

Solution 1: Simulation

We can directly simulate the process of generating the spiral matrix.

Define a 2D array ans to store the spiral matrix. Use i and j to represent the current row and column indices, and use k to represent the current direction index. dirs represents the mapping between direction indices and directions.

Starting from 1, fill each position in the matrix sequentially. After filling a position, calculate the row and column indices of the next position. If the next position is out of bounds or has already been filled, change the direction and then calculate the row and column indices of the next position.

The time complexity is O(n^2), where n is the side length of the matrix. Ignoring the space consumption of the answer array, the space complexity is O(1).

PythonJavaC++GoTypeScriptRustJavaScript
class Solution: def generateMatrix(self, n: int) -> List[List[int]]: ans = [[0] * n for _ in range(n)] dirs = (0, 1, 0, -1, 0) i = j = k = 0 for v in range(1, n * n + 1): ans[i][j] = v x, y = i + dirs[k], j + dirs[k + 1] if x < 0 or x >= n or y < 0 or y >= n or ans[x][y]: k = (k + 1) % 4 i, j = i + dirs[k], j + dirs[k + 1] return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !