λ°μν
π€λ¬Έμ ν΄κ²°
π¨ λ¬Έμ μμ μν€λλλ‘ κ·Έλλ‘ νμλ€. (ꡬν)
π« visited λΌλ 3μ°¨μ λ°°μ΄μ λ§λ λ€. μ μΌ μμͺ½μ μμμλ 'U','D','R','L' μ΄ λ€μ΄κ° μ μλλ° ν΄λΉ μμΉ(i, j) μμ μ΄λν λ°©ν₯μ λ΄κ³ μλ€. μΈμ΄ν΄μ΄ λ€λ₯΄λ©΄ μ λλ‘ μ΄λκ²½λ‘κ° νλλΌλ λκ°μκ² λμ¬ μ μκΈ° λλ¬Έμ. μ΄λν λ UDRL μ΄ μλμ§ νμΈμ νκ³ μ΄λνλ€.
π»μμ€ μ½λ
def solution(grid):
answer = []
N, M = len(grid), len(grid[0])
visited = [[set() for _ in range(M)] for _ in range(N)]
# U, D, L, R
for i in range(N):
for j in range(M):
for k in 'UDLR':
cnt = 0
while True:
if k in visited[i][j]: # μ΄λ―Έ μ΄λνλ μ μ΄ μλμ§ νμΈ
break
visited[i][j].add(k) # μλ€λ©΄ μΈμ΄ν΄ μμ
cnt += 1
# μ΄λ
if k == 'U':
i -= 1
if i < 0:
i = N - 1
elif k == 'D':
i += 1
if i == N:
i = 0
elif k == 'L':
j -= 1
if j < 0:
j = M - 1
elif k == 'R':
j += 1
if j == M:
j = 0
# λ€μ λ°©ν₯ 체ν¬
if grid[i][j] == 'L':
if k == 'U':
k = 'L'
elif k == 'D':
k = 'R'
elif k == 'L':
k = 'D'
elif k == 'R':
k = 'U'
elif grid[i][j] == 'R':
if k == 'U':
k = 'R'
elif k == 'D':
k = 'L'
elif k == 'L':
k = 'U'
elif k == 'R':
k = 'D'
if cnt > 0:
answer.append(cnt)
return sorted(answer)
πλ¬Έμ νμΈ
μΆμ²: νλ‘κ·Έλλ¨Έμ€
λ§ν¬: λΉμ κ²½λ‘ μΈμ΄ν΄
λ°μν