https://www.acmicpc.net/problem/4963
4963๋ฒ: ์ฌ์ ๊ฐ์
์ ๋ ฅ์ ์ฌ๋ฌ ๊ฐ์ ํ ์คํธ ์ผ์ด์ค๋ก ์ด๋ฃจ์ด์ ธ ์๋ค. ๊ฐ ํ ์คํธ ์ผ์ด์ค์ ์ฒซ์งธ ์ค์๋ ์ง๋์ ๋๋น w์ ๋์ด h๊ฐ ์ฃผ์ด์ง๋ค. w์ h๋ 50๋ณด๋ค ์๊ฑฐ๋ ๊ฐ์ ์์ ์ ์์ด๋ค. ๋์งธ ์ค๋ถํฐ h๊ฐ ์ค์๋ ์ง๋
www.acmicpc.net
dfs๋ก ํ์๋๋ RecursionError๊ฐ ๋์.. ์ด์ ๋ฅผ ์ฐพ์๋ณด๋๊น
BOJ ์ฑ์ ์๋น์ค์์๋ ํ์ด์ฌ ์ต๋ ์ฌ๊ท ๊น์ด๊ฐ 1000์ผ๋ก ์ค์ ๋์ด ์๋ค๊ณ ํ๋ค.
๊ทธ๋ฌ๋๊น ํ ์ผ์ค์์ ์ฌ๊ท๋ฅผ 1000๋ฒ ์ด์ ์ํํ๋ ๊ฒ ์์๋๋ณด๋ค
\ํด๊ฒฐ๋ฒ์ ์ฌ๋ฌ ๊ฐ์ง๊ฐ ์๋๋ฐ ๊ทธ์ค์์ ์ ค ์ฌ์ด๊ฑฐ ์ ํํจ ^v^
import sys
sys.setrecursionlimit(10**6)
์ต๋์ฌ๊ท๊น์ด๋ฅผ ์์๋ก ๊ฒ๋ ํฐ ์๋ก ์ค์ ํด์ฃผ๋ฉด ๋!
import sys
sys.setrecursionlimit(10**6)
#์ํ์ข์ฐ๋๊ฐ์
dx = [-1, -1, -1, 0, 1, 1, 1, 0]
dy = [-1, 0, 1, 1, 1, 0, -1, -1]
def dfs(x, y):
#๋ฒ์๋ฅผ ๋ฒ์ด๋์ง ์์ผ๋ฉด์ ๋ฐฉ๋ฌธํ ์ ์์ผ๋ฉด
if 0 <= x < w and 0 <= y < h and graph[x][y] == 1:
graph[x][y] = 0 # ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ
for i in range(8):
nx = x + dx[i]
ny = y + dy[i]
dfs(nx, ny)
return True #์ฌ์ land์์๋ค ์ค ์ต์ด๋ก ๋ฐฉ๋ฌธํ๋ ์ ๋ง True๋ฅผ ๋ฆฌํด
return False
while True:
#h,w,๊ทธ๋ํ ์ ๋ณด ์
๋ ฅ๋ฐ๊ธฐ
h, w = map(int, input().split())
if w == 0 and h == 0:
break
graph = []
for i in range(w):
graph.append(list(map(int, input().split())))
#์ฌ์ ๊ฐ์ count
cnt = 0
for i in range(w):
for j in range(h):
if dfs(i, j) == True: #์ต์ด ๋ฐฉ๋ฌธ ์นธ์์์๋ง cnt๋ฅผ ์ฆ๊ฐ์์ผ์ค
cnt += 1
print(cnt)
๋ณดํต ํ, ์ด ์์๋ก ์ ๋ ฅ๋ฐ๋ ๊ฒ ๋ง์๋ฐ ์ด ๋ฌธ์ ๋ ์ด, ํ ์์ผ๋ก ์ ๋ ฅ๋ฐ๋๋
์ฝ๊ฐ ์ฐ์ฐํด์ ์ฌ๊ท๋ฅผ ์์ ์ฌ์ฉํ์ง ์๋ bfs๋ก๋ ํ์ด๋ดค๋ค
from collections import deque
dx = [-1, -1, -1, 0, 1, 1, 1, 0]
dy = [-1, 0, 1, 1, 1, 0, -1, -1]
def bfs(x,y):
if graph[x][y]==0: #์ด๋ฏธ ๋ฐฉ๋ฌธํ ์ ์์ผ๋ฉด false๋ฆฌํด
return False
graph[x][y]=0 #๋ฐฉ๋ฌธ ์ฒ๋ฆฌ
q=deque()
q.append((x,y))
while q:
a,b=q.popleft()
for i in range(8):
nx = a + dx[i]
ny = b + dy[i]
if 0<=nx<w and 0<=ny<h and graph[nx][ny]==1:
graph[nx][ny]=0
q.append((nx,ny))
return True #์ธ์ ํ ์นธ๋ค ๋ชจ๋ ๋ฐฉ๋ฌธ์ด ๋๋๋ฉด true๋ฆฌํด
while True:
h, w = map(int, input().split())
if w == 0 and h == 0:
break
graph = []
for i in range(w):
graph.append(list(map(int, input().split())))
cnt = 0
for i in range(w):
for j in range(h):
if bfs(i, j) == True:
cnt += 1
print(cnt)
'์๊ณ ๋ฆฌ์ฆ ๋ฌธ์ ํ์ด > DFS,BFS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค]2468๋ฒ: ์์ ์์ญ (0) | 2023.02.25 |
---|---|
[๋ฐฑ์ค]10026๋ฒ: ์ ๋ก์์ฝ (0) | 2023.02.24 |
[์ด์ฝํ ]๋ฏธ๋ก ํ์ถ / [๋ฐฑ์ค]2178๋ฒ: ๋ฏธ๋ก ํ์ (0) | 2023.02.23 |
[์ด์ฝํ ] ์๋ฃ์ ์ผ๋ ค ๋จน๊ธฐ (1) | 2023.02.23 |
dfs, bfs ํ์ด์ฌ ๊ตฌํ (0) | 2023.02.23 |