๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/boj

BOJ 4963 - ์„ฌ์˜ ๊ฐœ์ˆ˜

by HandHand 2021. 6. 15.

๋ฌธ์ œ

๋ฐฑ์ค€ ์˜จ๋ผ์ธ ์ €์ง€ - 4963๋ฒˆ

ํ’€์ด ๊ณผ์ •

์„ฌ๊ณผ ๋ฐ”๋‹ค์˜ ์ง€๋„๊ฐ€ ์ฃผ์–ด์งˆ ๋•Œ ์„ฌ์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.
BFS ๋ฅผ ์ด์šฉํ•ด์„œ ์ปดํฌ๋„ŒํŠธ์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•ด์ฃผ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ


import sys
from collections import deque


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


def in_range(x, y):
    return 0 <= x < H and 0 <= y < W


def bfs(x, y, visit):
    q = deque()

    visit[x][y] = 1
    q.append([x, y])

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

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

            if in_range(nx, ny) and board[nx][ny] and not visit[nx][ny]:
                visit[nx][ny] = 1
                q.append([nx, ny])


def solution():
    island = 0
    visit = [[0] * W for _ in range(H)]

    for x in range(H):
        for y in range(W):
            if board[x][y] and not visit[x][y]:
                island += 1
                bfs(x, y, visit)

    return island


if __name__ == '__main__':
    while True:
        W, H = list(map(int, sys.stdin.readline().split()))

        if [W, H] == [0, 0]:
            break

        board = [list(map(int, sys.stdin.readline().split())) for _ in range(H)]
        answer = solution()
        print(answer)
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > boj' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

BOJ 14950 - ์ •๋ณต์ž  (0) 2021.06.25
BOJ 1197 - ์ตœ์†Œ ์ŠคํŒจ๋‹ ํŠธ๋ฆฌ  (0) 2021.06.18
BOJ 5568 - ์นด๋“œ ๋†“๊ธฐ  (0) 2021.06.14
BOJ 5972 - ํƒ๋ฐฐ ๋ฐฐ์†ก  (0) 2021.06.10
BOJ 1613 - ์—ญ์‚ฌ  (0) 2021.06.09

๐Ÿ’ฌ ๋Œ“๊ธ€