알고리즘

[백준, 4963번] 섬의 개수

hminor 2023. 8. 20. 11:44

풀이

  • 단순히 '상하좌우'만 탐색하는 문제가 아닌 대각선까지 탐색을 하는 문제이기에
  • 좌표를 총 8개를 추가해 탐색하는 과정을 거쳤으며
  • 입력이 계속 주어지고, 마지막에는 0,0 의 입력이 주어지기에 
  • 조건을 추가해 멈출 수 있도록 해결 

 

import sys
from collections import deque
input = sys.stdin.readline

while True:
    w,h = map(int,input().split())
    if not w and not h: break
    arr = [list(map(int,input().rstrip('\n').split())) for _ in range(h)]
    visit = [[0]*w for _ in range(h)]
    result = 0
    for i in range(h):
        for j in range(w):
            if arr[i][j] and not visit[i][j]: # 방문하지 않은 땅
                result += 1
                q = deque([[i,j]])
                visit[i][j] = 1
                while q:
                    y,x = q.popleft() # bfs
                    for a,b in [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,1],[1,-1]]:
                        dy, dx = y+a, x+b
                        if 0<=dy<h and 0<=dx<w and arr[dy][dx] and not visit[dy][dx]:
                            q.append([dy,dx])
                            visit[dy][dx] = 1
    print(result)

'알고리즘' 카테고리의 다른 글

[백준, 13116번] 30번  (0) 2023.08.21
[백준, 9372번] 상근이의 여행  (0) 2023.08.21
[백준, 1325번] 효율적인 해킹  (0) 2023.08.18
[백준, 11724번] 연결 요소의 개수  (0) 2023.08.15
[백준, 1697번] 숨바꼭질  (0) 2023.08.15