개발공부/algorithm

[백준][python] 3055.탈출 - DP

so.py 2021. 4. 11. 16:38
 

3055번: 탈출

사악한 암흑의 군주 이민혁은 드디어 마법 구슬을 손에 넣었고, 그 능력을 실험해보기 위해 근처의 티떱숲에 홍수를 일으키려고 한다. 이 숲에는 고슴도치가 한 마리 살고 있다. 고슴도치는 제

www.acmicpc.net

나의 접근

너비 우선 탐색으로 한시간이 지날때마다 물에 대한 경로탐색 및 이동 후, 고슴도치에 대한 경로 탐색 및 이동을 진행해야한다. 

처음에는 단순 BFS로 구현했다가 당연히 시간초과가 떴다. Deque을 사용하고, 미리 선언해놓은 N 길이의 배열에 거리를 저장해준다.

from collections import deque

def bfs(x, y):
    q.append([x, y])
    mapp[x][y] = 1

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

    while q:
        qlen = len(q)
        while qlen:
            x, y = q.popleft()
            for i in range(4):
                nx = x + dx[i]
                ny = y + dy[i]
                if 0 <= nx < n and 0 <= ny < m:
                    if a[nx][ny] == '.' and mapp[nx][ny] == 0:
                        mapp[nx][ny] = mapp[x][y] + 1
                        q.append([nx, ny])
                    elif a[nx][ny] == 'D':
                        print(mapp[x][y])
                        return
            qlen -= 1
        water()

    print("KAKTUS")
    return

def water():
    qlen = len(wq)
    dx = [1, -1, 0, 0]
    dy = [0, 0, 1, -1]
    
    while qlen:
        x, y = wq.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < n and 0 <= ny < m:
                if a[nx][ny] == '.':
                    a[nx][ny] = '*'
                    wq.append([nx, ny])
        qlen -= 1

n, m = map(int, input().split())
a = [list(map(str, input())) for _ in range(n)]
mapp = [[0] * m for _ in range(n)]
q, wq = deque(), deque()

for i in range(n):
    for j in range(m):
        if a[i][j] == 'S':
            x1, y1 = i, j
            a[i][j] = '.'
        elif a[i][j] == '*':
            wq.append([i, j])

water()
bfs(x1, y1)