|
| 1 | +import sys |
| 2 | +input = sys.stdin.readline |
| 3 | +from collections import deque |
| 4 | + |
| 5 | +# 8방향 (상, 하, 좌, 우, 대각선 4개) |
| 6 | +dx = [-1, 1, 0, 0, -1, -1, 1, 1] |
| 7 | +dy = [0, 0, -1, 1, -1, 1, -1, 1] |
| 8 | + |
| 9 | +def bfs(x, y, graph, w, h): |
| 10 | + queue = deque([(x, y)]) |
| 11 | + graph[y][x] = 0 # 방문 처리 (1 → 0 변경) |
| 12 | + |
| 13 | + while queue: # 큐가 빌 때까지 반복 |
| 14 | + cx, cy = queue.popleft() # 현재 좌표 꺼내기 |
| 15 | + for i in range(8): # 8방향 탐색 |
| 16 | + nx, ny = cx + dx[i], cy + dy[i] # 새로운 좌표 계산 |
| 17 | + if 0 <= nx < w and 0 <= ny < h and graph[ny][nx] == 1: |
| 18 | + graph[ny][nx] = 0 # 방문 처리 |
| 19 | + queue.append((nx, ny)) # 큐에 추가 (다음에 탐색할 곳) |
| 20 | + |
| 21 | +while True: |
| 22 | + w, h = map(int, input().split()) |
| 23 | + if w == 0 and h == 0: |
| 24 | + break # 종료 조건 |
| 25 | + island = [list(map(int, input().split())) for _ in range(h)] |
| 26 | + |
| 27 | + count = 0 # 섬의 개수 |
| 28 | + for y in range(h): |
| 29 | + for x in range(w): |
| 30 | + if island[y][x] == 1: # 새로운 섬 발견 |
| 31 | + count += 1 |
| 32 | + bfs(x, y, island, w, h) # BFS 실행 |
| 33 | + |
| 34 | + print(count) |
0 commit comments