본문 바로가기

알고리즘/백준

[백준] 14891번 : 톱니바퀴

728x90

14891번: 톱니바퀴

해당 문제는 구현 문제로 주어진 문제의 조건에 따라 문제를 해결하면 된다.

해당 톱니바퀴에서 다른톱니바퀴를 돌릴 수 있는 재귀적인 로직이 있기때문에 재귀함수로 문제를 해결하였습니다.

현재 톱니바퀴 위치에서 각각의 극과 극을 확인하여 재귀함수를 호출할것인지 말것인지에 판단합니다.

move = (1, -1)
north = 0
right = 2
left = 6

def sumScore(graph):
    sum = 0
    for i in range(1, len(graph)):
        if graph[i][north] == '1':
            sum += (2)**(i-1)
            
    return sum 

def rightRotate(arr): # 시계방향
    temp = arr[-1]
    for i in range(len(arr)-2, -1, -1):
        arr[i+1] = arr[i]
    
    arr[0] = temp
    
def leftRotate(arr): # 반시계
    temp = arr[0]
    for i in range(1, len(arr)):
        arr[i-1] = arr[i]
        
    arr[-1] = temp

def dfs(node, direction):
    visited[node] = True
    for d in move:
        newnode = d + node
        if 4 >= newnode >= 1 and not visited[newnode]:
            # 극이 다르다면
            if node > newnode: # 좌측 톱니바퀴 인경우
                if graph[node][left] != graph[newnode][right]:
                    dfs(newnode, -direction)
            else: # 우측 톱니바퀴인경우
                if graph[node][right] != graph[newnode][left]:
                    dfs(newnode, -direction)
                    
    if direction == 1: # 시계방향
        rightRotate(graph[node])
    else: # 반시계 방향
        leftRotate(graph[node])

graph = [[] for _ in range(5)]

for i in range(1, 5):
    graph[i] = list(input())
    
K = int(input())
for _ in range(K):
    visited = [False for _ in range(5)]
    node, dir = map(int, input().split())
    dfs(node, dir)

print(sumScore(graph))
728x90

'알고리즘 > 백준' 카테고리의 다른 글

[백준] 18428번 : 감시 피하기  (0) 2023.10.20
[백준] 1405번 : 미친로봇  (0) 2023.10.20
[백준] 2504번 : 괄호의 값  (0) 2023.10.20
[백준] 2250번 : 트리의 높이와 너비  (0) 2023.10.20
백준 2239번 : 수도쿠  (1) 2023.10.19