Skip to content

Commit 33568af

Browse files
author
Sitesh Pattanaik
committed
Added new code in Arrays
1 parent 9033612 commit 33568af

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Arrays/Spiral_Matrix.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Complexity Analysis
2+
3+
# Time Complexity: O(N)O(N), where NN is the total number of elements in the input matrix. We add every element in the matrix to our final answer.
4+
5+
# Space Complexity: O(N)O(N), the information stored in seen and in ans.
6+
7+
8+
class Solution(object):
9+
def spiralOrder(self, matrix):
10+
if not matrix: return []
11+
R, C = len(matrix), len(matrix[0])
12+
seen = [[False] * C for _ in matrix]
13+
ans = []
14+
dr = [0, 1, 0, -1]
15+
dc = [1, 0, -1, 0]
16+
r = c = di = 0
17+
for _ in range(R * C):
18+
ans.append(matrix[r][c])
19+
seen[r][c] = True
20+
cr, cc = r + dr[di], c + dc[di]
21+
if 0 <= cr < R and 0 <= cc < C and not seen[cr][cc]:
22+
r, c = cr, cc
23+
else:
24+
di = (di + 1) % 4
25+
r, c = r + dr[di], c + dc[di]
26+
return ans

0 commit comments

Comments
 (0)