본문 바로가기
Problem Solving/Dijkstra & Floyd-Warshall

[다익스트라] 백준 266번: 미로만들기 / 골드 4

by ggyongi 2022. 3. 5.
반응형

https://www.acmicpc.net/problem/2665

 

2665번: 미로만들기

첫 줄에는 한 줄에 들어가는 방의 수 n(1 ≤ n ≤ 50)이 주어지고, 다음 n개의 줄의 각 줄마다 0과 1이 이루어진 길이가 n인 수열이 주어진다. 0은 검은 방, 1은 흰 방을 나타낸다.

www.acmicpc.net

import heapq

n = int(input())
table = []
for _ in range(n):
    table.append([int(x) for x in input()])

visited = []
for _ in range(n):
    visited.append([False for _ in range(n)])


dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]

q = []
start = [0, 0, 0]  # crush, x, y
visited[0][0] = True
heapq.heappush(q, start)

while q:
    crush, x, y = heapq.heappop(q)
    print(crush, x, y)

    if x == n-1 and y == n-1: #finish
        print(crush)
        quit()

    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]
        if 0<=nx<n and 0<=ny<n and not visited[nx][ny]:
            visited[nx][ny] = True

            if table[nx][ny] == 0: # black room
                heapq.heappush(q, [crush+1, nx, ny])
            elif table[nx][ny] == 1: # white
                heapq.heappush(q, [crush, nx, ny])

전형적인 다익스트라 문제!

crush(=충돌 횟수)로 우선순위 큐를 만들어 bfs 탐색을 해주면 된다.

 

비전공자 네카라 신입 취업 노하우

시행착오 끝에 얻어낸 취업 노하우가 모두 담긴 전자책!

kmong.com

댓글