File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ from collections import deque
2+
3+ """
4+ BFS의 아이디어를 차용하여 풀이
5+
6+ 끝에서부터 안쪽으로 돌아가야하기에 미리 돌아갈 방향 지정 : (dx, dy)
7+ 한칸씩 이동해가면서 범위 밖을 넘어갔거나 이미 visit한 데이터가 발견되면 방향을 꺾음
8+
9+ Tc : O(m*n)
10+ Sc : O(m*n)
11+ """
12+
13+ # r, d, l ,u
14+ dx = [0 ,1 ,0 ,- 1 ]
15+ dy = [1 ,0 ,- 1 ,0 ]
16+
17+ class Solution :
18+ def __init__ (self ):
19+ self .m = 0
20+ self .n = 0
21+
22+ def in_range (self , r , c ):
23+ if r < 0 or r >= self .m or c < 0 or c >= self .n :
24+ return False
25+ return True
26+
27+ def spiralOrder (self , matrix : List [List [int ]]) -> List [int ]:
28+ INF = int (1e9 )
29+ d = 0
30+ self .m , self .n = len (matrix ), len (matrix [0 ])
31+ r , c = 0 , 0
32+
33+ ret = []
34+
35+ for _ in range (self .m * self .n ):
36+ ret .append (matrix [r ][c ])
37+ if not self .in_range (r + dx [d ], c + dy [d ]) or matrix [r + dx [d ]][c + dy [d ]] == INF :
38+ d = (d + 1 )% 4
39+ matrix [r ][c ] = INF
40+ r , c = r + dx [d ], c + dy [d ]
41+
42+ return ret
43+
44+
You can’t perform that action at this time.
0 commit comments