본문 바로가기
알고리즘 문제풀이/백준

백준 16236

by Hoseok 2023. 4. 8.
728x90
반응형

 

코드

from collections import deque

n = int(input())
graph = []
for _ in range(n):
    graph.append(list(map(int, input().split())))

shark_size = 2
shark_x, shark_y = 0, 0
for i in range(n):
    for j in range(n):
        if graph[i][j] == 9:
            shark_x, shark_y = i, j
            graph[i][j] = 0  # 상어 위치는 빈칸으로 처리
            break

dx, dy = [-1, 0, 1, 0], [0, -1, 0, 1]  # 북, 서, 남, 동

def bfs():
    dist = [[-1] * n for _ in range(n)]
    q = deque([(shark_x, shark_y)])
    dist[shark_x][shark_y] = 0
    while q:
        x, y = q.popleft()
        for i in range(4):
            nx, ny = x + dx[i], y + dy[i]
            if nx < 0 or nx >= n or ny < 0 or ny >= n:
                continue
            if dist[nx][ny] != -1 or graph[nx][ny] > shark_size:
                continue
            dist[nx][ny] = dist[x][y] + 1
            q.append((nx, ny))
    return dist

def find(dist):
    x, y = 0, 0
    min_dist = 1e9
    for i in range(n):
        for j in range(n):
            if dist[i][j] != -1 and 1 <= graph[i][j] < shark_size:
                if dist[i][j] < min_dist:
                    x, y = i, j
                    min_dist = dist[i][j]
    if min_dist == 1e9:
        return None
    else:
        return x, y, min_dist

result = 0
ate = 0
while True:
    value = find(bfs())
    if value is None:
        print(result)
        break
    else:
        shark_x, shark_y = value[0], value[1]
        result += value[2]
        graph[shark_x][shark_y] = 0
        ate += 1
        if ate >= shark_size:
            shark_size += 1
            ate = 0

 

728x90
반응형

'알고리즘 문제풀이 > 백준' 카테고리의 다른 글

백준 2293  (0) 2023.04.11
백준 1463  (0) 2023.04.08
백준 14502  (0) 2023.04.07
백준 2178  (0) 2023.04.05
백준 2667  (0) 2023.04.05