Ginny H
Ginny
Ginny H

인기 글

태그

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Ginny H

Ginny

Algorithm/BFS&DFS

[BFS] 아기상어 (python)

2022. 6. 24. 14:42

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

 

16236번: 아기 상어

N×N 크기의 공간에 물고기 M마리와 아기 상어 1마리가 있다. 공간은 1×1 크기의 정사각형 칸으로 나누어져 있다. 한 칸에는 물고기가 최대 1마리 존재한다. 아기 상어와 물고기는 모두 크기를 가

www.acmicpc.net

 

이 문제는 먹을 물고기들을 탐색하는 BFS 과정을 거쳐야한다.

이때, 물고기들의 거리를 찾는 과정과 그 중 하나를 고르는 과정을 분리해서 구하자!

 

1. 매일 반복 -> 먹을 게 더 없을 경우 종료!

2. 현재 상어가 먹을 수 있는 물고기들의 거리 탐색 -> BFS

3. 그 중 거리가 가장 가까운 물고기 먹기!

 

from collections import deque
INF = 1e9
graph = []
n = int(input())
for i in range(n):
    graph.append(list(map(int, input().split())))
    for j in range(n):
        if graph[i][j] == 9:
            now_x, now_y = i, j
            graph[i][j] = 0

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

# 2번 모든 물고기들까지의 거리 탐색
def bfs():
    dist = [[-1] * n for _ in range(n)]
    q = deque([(now_x, now_y)])
    dist[now_x][now_y] = 0
    while q:
        x, y = q.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < n and 0 <= ny < n:
                if dist[nx][ny] == -1:
                    if graph[nx][ny] <= now_size:  # 지나갈 수 있는 경우 + 먹을 수 있는 경우
                        dist[nx][ny] = dist[x][y] + 1
                        q.append((nx, ny))
    return dist

# 3번 먹을 물고기 정하기
def find(dist):
    x, y = 0, 0
    min_dist = INF
    for i in range(n):
        for j in range(n):
            if dist[i][j] != -1 and 1 <= graph[i][j] < now_size: # 먹을 수 있는 경우만
                if dist[i][j] < min_dist:
                    x, y = i, j
                    min_dist = dist[i][j]
    if min_dist == INF:
        return None
    else:
        return x, y, min_dist


result = 0
ate = 0

# 1번 매시간 반복 -> 조건에 따라 종료!
while True:
    value = find(bfs())
    if value == None:
        print(result)
        break
    else:
        now_x, now_y = value[0],  value[1]
        result += value[2]
        graph[now_x][now_y] = 0
        ate += 1
        if ate >= now_size:
            now_size += 1
            ate = 0

'Algorithm > BFS&DFS' 카테고리의 다른 글

[DFS] 타겟 넘버 (python) - 프로그래머스  (0) 2022.06.25
[BFS] 경쟁적 전염 (python)  (0) 2022.06.24
[BFS] 블록 이동하기 (python)  (0) 2022.06.23
[BFS/DFS] 네트워크 (python) - 프로그래머스  (0) 2022.06.21
[BFS/DFS] 연구소 (python)  (0) 2022.06.21
    'Algorithm/BFS&DFS' 카테고리의 다른 글
    • [DFS] 타겟 넘버 (python) - 프로그래머스
    • [BFS] 경쟁적 전염 (python)
    • [BFS] 블록 이동하기 (python)
    • [BFS/DFS] 네트워크 (python) - 프로그래머스
    Ginny H
    Ginny H

    티스토리툴바