๐ŸŒฑ → ๐ŸŒณ

[Baekjoon] 4963. ์„ฌ์˜ ๊ฐœ์ˆ˜ - python ๋ณธ๋ฌธ

Algorithms

[Baekjoon] 4963. ์„ฌ์˜ ๊ฐœ์ˆ˜ - python

BAY 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