File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments