※ 2573 빙산
https://www.acmicpc.net/problem/2573
문제 해결 TIP
기존 bfs 알고리즘으로 탐색과 녹이기를 동시에 수행할 수 있다.
전체 코드
from collections import deque
import sys
input = sys.stdin.readline
dx = [-1,0,1,0]
dy = [0,1,0,-1]
N, M = map(int,input().split())
graph = []
year = 0
for i in range(N):
graph.append(list(map(int,input().split())))
def bfs(x,y):
queue = deque()
queue.append((x,y))
visited[x][y] = 1
while queue:
x, y = queue.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < N and 0 <= ny < M:
if graph[nx][ny] == 0:
visited[x][y] += 1
if visited[nx][ny] == 0 and graph[nx][ny] != 0:
queue.append((nx,ny))
visited[nx][ny] = 1
while True:
count = 0
visited = [[0] * M for _ in range(N)]
#탐색
for i in range(N):
for j in range(M):
if visited[i][j] == 0 and graph[i][j] > 0:
bfs(i,j)
count += 1
#녹이기
for i in range(N):
for j in range(M):
if visited[i][j] != 0:
graph[i][j] -= (visited[i][j] - 1)
if graph[i][j] < 0:
graph[i][j] = 0
#덩어리 검사
if count >= 2:
print(year)
break
if count == 0:
print(0)
break
year += 1
- 비기너 문제 : 회상 https://www.acmicpc.net/problem/32953
- 미들러 문제 : DFS와 BFS https://www.acmicpc.net/problem/1260
- 챌린저 문제 : 한 번 남았다 https://www.acmicpc.net/problem/13317
'Python > DFS&BFS' 카테고리의 다른 글
99클럽 코테 스터디 9일차 TIL + 백준 1707 이분 그래프 (파이썬) (0) | 2025.01.23 |
---|---|
99클럽 코테 스터디 8일차 TIL + 백준 2667 단지번호붙이기 (파이썬) (0) | 2025.01.22 |
99클럽 코테 스터디 7일차 TIL + 백준 1697 숨바꼭질 (파이썬) (0) | 2025.01.21 |
99클럽 코테 스터디 6일차 TIL + 백준 1260 DFS와 BFS (파이썬) (0) | 2025.01.21 |
[Algorithm] 백준 1261 알고스팟 | 파이썬 BFS (0) | 2024.09.11 |
댓글