보물창고 블로그

프로그래머스 빛의 경로 사이클 풀이 With Python 본문

알고리즘 풀이/프로그래머스

프로그래머스 빛의 경로 사이클 풀이 With Python

홋 메 2022. 2. 23. 22:36
728x90

문제 링크: https://programmers.co.kr/learn/courses/30/lessons/86052

 

코딩테스트 연습 - 빛의 경로 사이클

각 칸마다 S, L, 또는 R가 써져 있는 격자가 있습니다. 당신은 이 격자에서 빛을 쏘고자 합니다. 이 격자의 각 칸에는 다음과 같은 특이한 성질이 있습니다. 빛이 "S"가 써진 칸에 도달한 경우, 직진

programmers.co.kr

문제의 핵심은 루프를 체크하는 것입니다. 현재 위치의 x,y 좌표값과 방향 d를 한묶음으로 하여 루프를 체크하였습니다. 소스코드는 아래와 같습니다.

 

def solution(grid):
    answer = []
    h = len(grid)
    w = len(grid[0])
    dx = [-1, 0, 1, 0]
    dy = [0, 1, 0, -1]
    dic = {}
    for i in range(h):
        for j in range(w):
            for d in range(4):
                if (i, j, d) not in dic:
                    count = 0
                    x, y, direction = i, j, d
                    while (x, y, direction) not in dic:
                        dic[(x, y, direction)] = 1
                        count += 1
                        if grid[x][y] == 'L':
                            direction = (direction - 1) % 4
                        elif grid[x][y] == 'R':
                            direction = (direction + 1) % 4
                        x = (x + dx[direction]) % h
                        y = (y + dy[direction]) % w
                    answer.append(count)
    answer.sort()
    return answer

 

 

Comments