Search
Duplicate

빛의 경로 사이클

문제 설명 및 제한사항

아이디어 및 해결 방법

코드

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
Python
복사

출처

프로그래머스 코딩테스트 연습 https://school.programmers.co.kr/learn/challenges