문제출처 : https://school.programmers.co.kr/learn/courses/30/lessons/86052
접근법
A 노드에서 좌 방향으로 빛을 쏘아 시작한 사이클
B 노드에서 빛이 들어와 A 노드에서 좌 방향으로 빛이 다시 나가는 사이클
2개의 사이클은 똑같은 사이클이다. 즉 어떤 사이클에서 특정 노드에서 빛이 나가는 방향을 확인했다면 더 이상 다른 사이클에서 나올 확률은 0이다.
코드
def solution(grid): global answer answer = [] # LC = { "R":"T" ,"L":"B" ,"T":"L" ,"B":"R" } RC = { "R":"B" ,"L":"T" ,"T":"R" ,"B":"L" } # directions = [ [ ["L","R","T","B"] for j in range(len(grid[0])) ] for i in range(len(grid)) ] # for i in range(len(grid)): for j in range(len(grid[0])): while( directions[i][j] ): n_i,n_j = i,j direction = directions[i][j][0] count = 0 while(1): # 루프 cycle = grid[n_i][n_j] # S,L,R if( count ): if( cycle == "L" ): direction = LC[direction] elif( cycle == "R" ): direction = RC[direction] # if( direction in directions[n_i][n_j] ): directions[n_i][n_j].remove(direction) else: # 사이클 끝 answer.append(count) break # if( direction == "L" ): n_j = n_j-1 if n_j > 0 else len(grid[0])-1 elif( direction == "R" ): n_j = n_j+1 if n_j < len(grid[0])-1 else 0 elif( direction == "T" ): n_i = n_i-1 if n_i > 0 else len(grid)-1 else: # B n_i = n_i+1 if n_i < len(grid)-1 else 0 count += 1 # return sorted(answer)