Skip to content

Commit 642e019

Browse files
authored
Merge pull request #1840 from PradnyaGaitonde/PradnyaGaitonde-patch-22
Create 0059-spiral-matrix-II.md
2 parents 24d8962 + 7e93a07 commit 642e019

File tree

1 file changed

+130
-0
lines changed

1 file changed

+130
-0
lines changed
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
---
2+
id: spiral-matrix-II
3+
title: Spiral Matrix II(LeetCode)
4+
sidebar_label: 0059-Spiral Matrix II
5+
tags:
6+
- Array
7+
- Matric
8+
- Simulation
9+
description: Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
10+
---
11+
12+
## Problem Statement
13+
14+
Given a positive integer `n`, generate an `n x n` matrix filled with elements from `1` to `n2` in spiral order.
15+
16+
### Examples
17+
18+
**Example 1:**
19+
20+
![image](https://github.com/PradnyaGaitonde/codeharborhub.github.io/assets/116059908/946cfd25-b503-4cce-8d8d-b8dca3f91631)
21+
22+
```plaintext
23+
Input: n = 3
24+
Output: [[1,2,3],[8,9,4],[7,6,5]]
25+
```
26+
27+
**Example 2:**
28+
29+
```plaintext
30+
Input: n = 1
31+
Output: [[1]]
32+
```
33+
34+
### Constraints
35+
36+
- `1 <= n <= 20`
37+
38+
## Solution
39+
40+
Generating a spiral matrix is an interesting problem that involves filling a matrix in a spiral order. Here, we will discuss three solutions: building the matrix inside-out using two different approaches and walking the spiral path.
41+
42+
### Approach 1: Build it Inside-Out
43+
44+
#### Algorithm
45+
46+
1. Initialize an empty list `A` and set `lo` to `n*n + 1`.
47+
2. While `lo > 1`:
48+
* Calculate `lo` and `hi`.
49+
* Add a new row of numbers ranging from `lo` to `hi` to `A`.
50+
* Rotate `A` clockwise by using `zip` and list slicing.
51+
3. Return the constructed matrix `A`.
52+
53+
#### Implementation
54+
55+
```Python
56+
def generateMatrix(self, n):
57+
A, lo = [], n*n+1
58+
while lo > 1:
59+
lo, hi = lo - len(A), lo
60+
A = [range(lo, hi)] + list(zip(*A[::-1]))
61+
return A
62+
```
63+
64+
### Complexity Analysis
65+
66+
- **Time complexity**: $O(N^2)$
67+
- **Space complexity**: $O(N^2)$
68+
69+
### Approach 2: Ugly Inside-Out
70+
71+
#### Algorithm
72+
73+
1. Initialize `A` with a single element `n*n`.
74+
2. While the first element of `A` is greater than 1:
75+
* Add a new row of numbers from `A[0][0] - len(A)` to `A[0][0]`.
76+
* Rotate `A` clockwise by using `zip` and list slicing.
77+
3. Return `A` multiplied by `(n > 0)` to handle the `n=0` case.
78+
79+
#### Implementation
80+
81+
```Python
82+
def generateMatrix(self, n):
83+
A = [[n*n]]
84+
while A[0][0] > 1:
85+
A = [range(A[0][0] - len(A), A[0][0])] + list(zip(*A[::-1]))
86+
return A * (n > 0)
87+
88+
```
89+
90+
### Complexity Analysis
91+
92+
- **Time complexity**: $O(N^2)$
93+
- **Space complexity**: $O(N^2)$
94+
95+
### Approach 3: Walk the Spiral
96+
97+
#### Algorithm
98+
99+
1. Initialize the matrix `A` with zeros.
100+
2. Set the initial position and direction.
101+
3. For each number from 1 to `n*n`:
102+
* Fill the current cell with the current number.
103+
* Check if the next cell in the current direction is out of bounds or already filled.
104+
* If so, change the direction.
105+
* Move to the next cell.
106+
4. Return the filled matrix `A`.
107+
108+
#### Implementation
109+
110+
```Python
111+
def generateMatrix(self, n):
112+
A = [[0] * n for _ in range(n)]
113+
i, j, di, dj = 0, 0, 0, 1
114+
for k in range(n*n):
115+
A[i][j] = k + 1
116+
if A[(i + di) % n][(j + dj) % n]:
117+
di, dj = dj, -di
118+
i += di
119+
j += dj
120+
return A
121+
```
122+
123+
### Complexity Analysis
124+
125+
- **Time complexity**: $O(N^2)$
126+
- **Space complexity**: $O(N^2)$
127+
128+
### Conclusion
129+
130+
All three solutions effectively generate a spiral matrix, with varying approaches and code readability. The inside-out solutions (Solutions 1 and 2) leverage matrix rotation and range operations, while the spiral walk solution (Solution 3) explicitly manages the matrix and directions to fill the numbers. Each approach has its own merits and can be chosen based on preference for readability and code complexity.

0 commit comments

Comments
 (0)