문제
![](https://velog.velcdn.com/images%2Fcosmos%2Fpost%2Fee6d4e75-d937-4bcf-b5d6-5c9d0f28635e%2F%E1%84%89%E1%85%B3%E1%84%8F%E1%85%B3%E1%84%85%E1%85%B5%E1%86%AB%E1%84%89%E1%85%A3%E1%86%BA%202022-02-25%20%E1%84%8B%E1%85%A9%E1%84%8C%E1%85%A5%E1%86%AB%203.29.01.png)
풀이
- 그래프를 순회하며 영역탐지를 해야하는 문제이다.
DFS
로 구현하였다.
- DFS를 사용하면 재귀 호출을 해야하기 때문에 시간 초과 판정을 피해야해서
sys 모듈
의 setrecursionlimit
함수를 사용하였다.
코드
from sys import stdin, setrecursionlimit
setrecursionlimit(10**5)
input = stdin.readline
dx = [1, -1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, -1, 1, -1, -1, 1, 1]
def dfs(x, y):
graph[x][y] = 0
for i in range(8):
nx = x + dx[i]
ny = y + dy[i]
if nx <= -1 or ny <= -1 or nx >= h or ny >= w:
continue
if graph[nx][ny] == 1:
dfs(nx, ny)
return False
while True:
w, h = map(int, input().split())
if w == 0 and h == 0:
break
graph = [list(map(int, input().split())) for _ in range(h)]
result = 0
for x in range(h):
for y in range(w):
if graph[x][y] == 1:
dfs(x, y)
result += 1
print(result)
결과
![](https://velog.velcdn.com/images%2Fcosmos%2Fpost%2F2d3b5acd-98f7-4515-b5da-a6a1775743cf%2F%E1%84%89%E1%85%B3%E1%84%8F%E1%85%B3%E1%84%85%E1%85%B5%E1%86%AB%E1%84%89%E1%85%A3%E1%86%BA%202022-02-25%20%E1%84%8B%E1%85%A9%E1%84%8C%E1%85%A5%E1%86%AB%204.14.05.png)
출처 & 깃허브
BOJ 4963
github