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