섬의 개수 – 실버2

2023. 1. 3. 16:50코딩 테스트 준비

728x90
반응형

대각선 루트를 추가하면 되는 간단한 bfs 문제

import sys
from collections import deque

def bfs(y, x, land_map):
    q = deque()
    q.append((y, x))
    land_map[y][x] = 0
    while q:
        y, x = q.popleft()
        for dx, dy in d:
            X, Y = x + dx, y + dy
            if 0 <= X < w and 0 <= Y < h and land_map[Y][X] == 1:
                land_map[Y][X] = 0
                q.append((Y, X))

input = sys.stdin.readline
d = [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1),(-1,1),(1,-1),(-1,-1)]
while True:
    w, h = map(int, input().split())
    if w == 0 and h == 0:
        break
    land_map = [list(map(int,input().split())) for _ in range(h)]
    ans = 0
    for i in range(h):
        for j in range(w):
            if land_map[i][j] == 1:
                ans += 1
                bfs(i, j, land_map)
    print(ans)
728x90
반응형

'코딩 테스트 준비' 카테고리의 다른 글

순열 싸이클 - 실버 3  (0) 2023.01.04
피보나치 수 2 – 브론즈 1  (0) 2023.01.03
음식물 피하기 – 실버1  (0) 2023.01.03
연결 요소의 개수 – 실버 2  (0) 2023.01.02
미로 탐색 – 실버 1  (0) 2023.01.02