์ค๋ฒ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 ๋ฐฑ์ค(4963๋ฒ) - ์ฌ์ ๊ฐ์