title: "[프로그래머스] 빛의 경로 사이클 Python 파이썬 해설 (Level 2) - 이도훈"
cleanUrl: "programmers/86052"
description: "프로그래머스 Level 2 문제 [빛의 경로 사이클]의 풀이를 정리합니다."
UP, DOWN, RIGHT, LEFT = 0, 1, 2, 3
DIRECTIONS = [UP, DOWN, RIGHT, LEFT]
TURN = {
(UP, 'S'): UP, (UP, 'L'): LEFT, (UP, 'R'): RIGHT,
(DOWN, 'S'): DOWN, (DOWN, 'L'): RIGHT, (DOWN, 'R'): LEFT,
(RIGHT, 'S'): RIGHT, (RIGHT, 'L'): UP, (RIGHT, 'R'): DOWN,
(LEFT, 'S'): LEFT, (LEFT, 'L'): DOWN, (LEFT, 'R'): UP,
}
def solution(grid):
R, C = len(grid), len(grid[0])
answer = []
# R x C x 4 인 3차원 배열 visited를 만듭니다.
visited = [[[False, False, False, False] for i in range(C)] for j in range(R)]
for r in range(R):
for c in range(C):
for d in DIRECTIONS:
if visited[r][c][d]:
continue
l = 0
cr, cc, cd = r, c, d
while True:
visited[cr][cc][cd] = True
if cd == UP:
cr -= 1
if cr == -1:
cr = R-1
cd = TURN[(cd, grid[cr][cc])]
elif cd == RIGHT:
cc += 1
if cc == C:
cc = 0
cd = TURN[(cd, grid[cr][cc])]
elif cd == DOWN:
cr += 1
if cr == R:
cr = 0
cd = TURN[(cd, grid[cr][cc])]
elif cd == LEFT:
cc -= 1
if cc == -1:
cc = C-1
cd = TURN[(cd, grid[cr][cc])]
l += 1
if visited[cr][cc][cd]:
break
answer.append(l)
answer.sort()
return answer
프로그래머스 코딩테스트 연습 https://school.programmers.co.kr/learn/challenges