๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/๋ฐฑ์ค€(BOJ)

[ ํŒŒ์ด์ฌ(python) ] ๋ฐฑ์ค€ 4963 - ์„ฌ์˜ ๊ฐœ์ˆ˜(BFS)

by YWTechIT 2021. 4. 20.
728x90

๐Ÿ“Œ ๋ฐฑ์ค€ 4963 - ์„ฌ์˜ ๊ฐœ์ˆ˜

๋ฌธ์ œ ์„ค๋ช…


๐Ÿ’ก ๋‚˜์˜ ํ’€์ด

BFS ํ˜น์€ DFS๋งŒ ์ž˜ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค๋ฉด ์–ด๋ ค์šด ๋ฌธ์ œ๋Š” ์•„๋‹ˆ๋‹ค. ๋‹ค๋งŒ, ๊ธฐ์กด ๋ฌธ์ œ์—์„œ๋Š” ์ƒ, ํ•˜, ์ขŒ, ์šฐ ํŒจํ„ด์ด ๋“ฑ์žฅํ–ˆ๋‹ค๋ฉด ์ด๋ฒˆ์—๋Š” ๋Œ€๊ฐ์„  ํŒจํ„ด์ด ๋“ฑ์žฅํ–ˆ๋‹ค. ์ด์™• ๋“ฑ์žฅํ–ˆ์œผ๋‹ˆ ๋‹ค์Œ ์„ธ ๊ฐ€์ง€ ํŒจํ„ด์„ ์•Œ์•„๋ณด์ž.

728x90
  1. ์ƒ, ํ•˜, ์ขŒ, ์šฐ ํŒจํ„ด
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
  1. ๋Œ€๊ฐ์„  + ์ƒ, ํ•˜, ์ขŒ, ์šฐ ํŒจํ„ด
dx = [-1, -1, -1, 0, 0, 1, 1, 1]
dy = [-1, 0, 1, -1, 1, -1, 0, 1]
  1. ๋Œ€๊ฐ์„  ํŒจํ„ด
dx = [-1, -1, 1, 1]
dy = [-1, 1, -1, 1]

ํŒจํ„ด2๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์‰ฝ๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  while๋ฌธ ์ข…๋ฃŒ์กฐ๊ฑด์€ ์ž…๋ ฅ์ด 0, 0์ด์–ด์•ผ ํ•˜๋Š”๋ฐ, ์ด๋Š” if not w and not h์กฐ๊ฑด์„ ์ฃผ๋ฉด ์‰ฝ๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

from collections import deque

def bfs(x, y):
    queue = deque()
    queue.append((x, y))
    visited[x][y] = True

    while queue:
        x, y = queue.popleft()

        for i in range(8):
            nx = x + dx[i]
            ny = y + dy[i]

            if 0 <= nx < h and 0 <= ny < w:
                if graph[nx][ny] == 1 and not visited[nx][ny]:
                    visited[nx][ny] = True
                    queue.append((nx, ny))

dx = [-1, -1, -1, 0, 0, 1, 1, 1]
dy = [-1, 0, 1, -1, 1, -1, 0, 1]

while True:
    w, h = map(int, input().split())
    if not w and not h:
        break
    graph = [list(map(int, input().split())) for _ in range(h)]
    visited = [[False] * w for _ in range(h)]
    cnt = 0

    for i in range(h):
        for j in range(w):
            if graph[i][j] == 1 and not visited[i][j]:
                bfs(i, j)
                cnt += 1
    print(cnt)
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€