์‹ค๋ฒ„2 : DFS ๋ฌธ์ œ์ด๋‹ค.

ํ’€์ด

๊ทธ๋ƒฅ ๊ตฌํ˜„ํ•˜๋ผ๋Š” ๋Œ€๋กœ ํƒ์ƒ‰ํ•ด์„œ answer๋ฅผ ๋Š˜๋ ค์ฃผ๋ฉด ๋œ๋‹ค.

Code

import sys
sys.setrecursionlimit(int(1e6))
d = [[1, 0], [0, 1], [-1, 0], [0, -1], [-1, -1], [-1, 1], [1, -1], [1, 1]]
 
 
def DFS(y, x, visited, board, num):
    land = board[y][x]
    for dy, dx in d:
        ny, nx = y + dy, x + dx
        # ๋ฐ”๊นฅ์œผ๋กœ ์•ˆ๋‚˜๊ฐ€๊ณ , ๋‹ค์Œ์ด ๋•…์ด๊ณ , ํ•ด๋‹น ์ง€์—ญ์„ ์นด์šดํŠธํ•˜์ง€ ์•Š์•˜๋‹ค๋ฉด
        if (
            0 <= ny < h
            and 0 <= nx < w
            and board[ny][nx] == land
            and visited[ny][nx] == 0
        ):
            visited[ny][nx] = num
            DFS(ny, nx, visited, board, num)
 
 
while True:
    w, h = map(int, input().split())
    if w == 0 and h == 0:
        break
 
    board = [list(map(int, input().split())) for _ in range(h)]
    visited = [[0 for _ in range(w)] for _ in range(h)]
    num = 0
    for i in range(h):
        for j in range(w):
            # ๋ฐ”๋‹ค๊ฑฐ๋‚˜, ์ด๋ฏธ ๋ฐฉ๋ฌธํ–ˆ๋‹ค๋ฉด ๋‹ค์Œ
            if board[i][j] == 0 or visited[i][j] != 0:
                continue
 
            # ๋•…์ด๊ณ , ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ ํƒ์ƒ‰
            DFS(i, j, visited, board, num + 1)
            num += 1
    print(num)
 

Reference