λ¬Έμ
https://www.acmicpc.net/problem/4963
4963λ²: μ¬μ κ°μ
μ λ ₯μ μ¬λ¬ κ°μ ν μ€νΈ μΌμ΄μ€λ‘ μ΄λ£¨μ΄μ Έ μλ€. κ° ν μ€νΈ μΌμ΄μ€μ 첫째 μ€μλ μ§λμ λλΉ wμ λμ΄ hκ° μ£Όμ΄μ§λ€. wμ hλ 50λ³΄λ€ μκ±°λ κ°μ μμ μ μμ΄λ€. λμ§Έ μ€λΆν° hκ° μ€μλ μ§λ
www.acmicpc.net
νμ΄
# λ°±μ€ 4963λ² λ¬Έμ - μ¬μ κ°μ
from collections import deque
dx = [0,0,-1,1,1,-1,1,-1]
dy = [1,-1,0,0,1,-1,-1,1]
def bfs(graph, x, y):
queue = deque()
graph[x][y] = 0
queue.append((x, y))
global cnt
while queue:
x, y = queue.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
queue.append((nx, ny))
while True:
w, h = map(int, input().split())
graph = []
if w == 0 and h == 0:
break
for _ in range(h):
graph.append(list(map(int, input().split())))
result = []
cnt = 1
answer = 0
for i in range(h):
for j in range(w):
if graph[i][j] == 1:
bfs(graph, i,j)
answer += 1
print(answer)
'ποΈ Algorithm > π© λ°±μ€' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
π© [λ°±μ€] [Python] [BFS/DFS] 7569λ²_ν λ§ν (0) | 2022.11.17 |
---|---|
π© [λ°±μ€] [Python] [BFS/DFS] 10026λ²_μ λ‘μμ½ (0) | 2022.11.17 |
π© [λ°±μ€] [Python] [BFS/DFS] 7562λ²_λμ΄νΈμ μ΄λ (0) | 2022.11.16 |
π© [λ°±μ€] [Python] [BFS/DFS] 14502λ²_μ°κ΅¬μ (0) | 2022.11.16 |
π© [λ°±μ€] [Python] [BFS/DFS] 18352λ²_νΉμ 거리μ λμ μ°ΎκΈ° (0) | 2022.11.16 |