알고리즘/[Python] 백준

(Python) 백준 3055번 : 탈출

출처 : https://www.acmicpc.net/problem/3055

 

3055번: 탈출

문제 사악한 암흑의 군주 이민혁은 드디어 마법 구슬을 손에 넣었고, 그 능력을 실험해보기 위해 근처의 티떱숲에 홍수를 일으키려고 한다. 이 숲에는 고슴도치가 한 마리 살고 있다. 고슴도치는 제일 친한 친구인 비버의 굴로 가능한 빨리 도망가 홍수를 피하려고 한다. 티떱숲의 지도는 R행 C열로 이루어져 있다. 비어있는 곳은 '.'로 표시되어 있고, 물이 차있는 지역은 '*', 돌은 'X'로 표시되어 있다. 비버의 굴은 'D'로, 고슴도치의 위치는 'S'로 나

www.acmicpc.net


 

(Python) 백준 1055번 탈출

(Python) 백준 1055번 : 탈출

출처 : https://www.acmicpc.net/problem/3055

  • 알고리즘 분류
    • BFS
    • 시뮬레이션

In [79]:
from collections import deque
In [80]:
def flow_water(array):
    x_queue = deque()
    for a,b in array:
        for i in range(4):
            na, nb = a+dx[i], b+dy[i]
            if not(0<=na<n and 0<=nb<m): continue
            if board[na][nb]=='.' and water_board[na][nb]==False:
                x_queue.append((na, nb))
                water_board[na][nb]=True
    return x_queue
In [81]:
def bfs(s_queue, water):
    time = 0
    while s_queue:
        queue = deque()
        time = time + 1
        water = flow_water(water)
        while s_queue:
            sx,sy = s_queue.popleft()
            for i in range(4):
                new_sx, new_sy = sx+dx[i], sy+dy[i]
                if not(0<=new_sx<n and 0<=new_sy<m): continue
                if water_board[new_sx][new_sy] == True: continue
                if board[new_sx][new_sy]=='X': continue
                if board[new_sx][new_sy]=='.' and water_board[new_sx][new_sy]==False and (new_sx, new_sy) not in visited:
                    visited.add((new_sx, new_sy))
                    queue.append((new_sx, new_sy))
                    continue
                if board[new_sx][new_sy]=='D':
                    return time
        s_queue = queue.copy()
        queue.clear()
    return 'KAKTUS'
In [82]:
if __name__ == '__main__':
    n,m = map(int, input().split())
    board = [list(input()) for _ in range(n)]

    water = deque()
    s_queue = deque()
    visited = set()
    water_board = [[False]*m for _ in range(n)]
    for i in range(n):
        for j in range(m):
            if board[i][j]=='*':
                water.append((i,j))
                water_board[i][j]=True
            elif board[i][j]=='S':
                s_queue.append((i,j))
                visited.add((i,j))
                board[i][j]='.'

    # 동 남 서 북
    dx = (0,1,0,-1)
    dy = (1,0,-1,0)
    print(bfs(s_queue, water))
3 6
D...*.
.X.X..
....S.
6