Algorithms
[Baekjoon] 4963. μ¬μ κ°μ - python
thals0
2023. 10. 27. 10:36
728x90
https://www.acmicpc.net/problem/4963
4963λ²: μ¬μ κ°μ
μ λ ₯μ μ¬λ¬ κ°μ ν μ€νΈ μΌμ΄μ€λ‘ μ΄λ£¨μ΄μ Έ μλ€. κ° ν μ€νΈ μΌμ΄μ€μ 첫째 μ€μλ μ§λμ λλΉ wμ λμ΄ hκ° μ£Όμ΄μ§λ€. wμ hλ 50λ³΄λ€ μκ±°λ κ°μ μμ μ μμ΄λ€. λμ§Έ μ€λΆν° hκ° μ€μλ μ§λ
www.acmicpc.net
μ½λ
from collections import deque
dx = [1,0,0,-1,1,1,-1,-1]
dy = [0,1,-1,0,1,-1,-1,1]
def bfs(a,b):
q = deque()
q.append((a,b))
graph[a][b] = 0
while q:
x,y = q.popleft()
for i in range(8):
nx = x + dx[i]
ny = y + dy[i]
if nx < 0 or nx >= h or ny < 0 or ny >= w:
continue
if graph[nx][ny] == 1:
graph[nx][ny] = 0
q.append((nx,ny))
return
while True:
w,h = map(int, input().split())
if w == 0 and h == 0:
break
graph = []
for _ in range(h):
graph.append(list(map(int, input().split())))
cnt = 0
for i in range(h):
for j in range(w):
if graph[i][j] == 1:
bfs(i,j)
cnt += 1
print(cnt)
μ²μμ κΈ°λ³Έ bfsλΌκ³ μκ°νκ³ νμλλ°
λ¬Έμ λ₯Ό λ€μ μ½μ΄λ³΄λ “λκ°μ ”λ κ±Έμ΄κ° μ μλ μ¬κ°νμ΄μμ
dx = [1,0,0,-1,1,1,-1,-1] dy = [0,1,-1,0,1,-1,-1,1]
μ΄λ κ² λ°κΏμ€μΌλ‘μ λ¬Έμ ν΄κ²° ~>>
728x90