๋ฌธ์
๋ฐฑ์ค ์จ๋ผ์ธ ์ ์ง - 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 |
๐ฌ ๋๊ธ