Skip to content

Commit 5dcda46

Browse files
committed
Python solution for Spiral matrix in DSA450
1 parent 8ccf4ca commit 5dcda46

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

DSA 450 GFG/spiral_matrix.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Link to the problem : https://leetcode.com/problems/spiral-matrix/
2+
3+
class Solution:
4+
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
5+
res = []
6+
n = len(matrix)
7+
if (n == 0):
8+
return matrix
9+
10+
# Initialize the Boundaries
11+
rowBeg = 0
12+
rowEnd = len(matrix) - 1
13+
colBeg = 0
14+
colEnd = len(matrix[0]) - 1
15+
16+
#Right Traversal
17+
while(rowBeg <= rowEnd and colBeg <= colEnd):
18+
19+
for i in range(colBeg , colEnd + 1):
20+
res.append(matrix[rowBeg][i])
21+
rowBeg += 1
22+
23+
#Bottom Traversal
24+
for i in range(rowBeg , rowEnd + 1):
25+
res.append(matrix[i][colEnd])
26+
colEnd -= 1
27+
28+
#Left Traversal
29+
30+
if(rowBeg <= rowEnd):
31+
for i in range(colEnd , colBeg - 1 , -1 ):
32+
res.append(matrix[rowEnd][i])
33+
rowEnd -= 1
34+
35+
#Upward Traversal
36+
37+
if(colBeg <= colEnd):
38+
for i in range(rowEnd , rowBeg - 1 , -1):
39+
res.append(matrix[i][colBeg])
40+
colBeg += 1
41+
42+
return res

0 commit comments

Comments
 (0)