๋ฐ์ํ
๐ป ๋ฐฑ์ค 1012๋ฒ [์ ๊ธฐ๋ ๋ฐฐ์ถ]
ํ์ด)
import sys
sys.setrecursionlimit(100000000)
T = int(input())
cnt_lst = []
for t in range(T) :
m,n,k = map(int,input().split())
cab = [list(map(int,input().split())) for _ in range(k)]
map_ = [[0]*m for _ in range(n)]
for i,j in cab :
map_[j][i] = 1
visited = [[0]*m for _ in range(n)]
def dfs(x,y,visited) :
# 1. ๋ฐฉ๋ฌธํ ๋
ธ๋์ธ์ง ํ์ธ
if not visited[x][y] :
# ๋ฐฉ๋ฌธ์ฒ๋ฆฌ
visited[x][y] = 1
if map_[x][y] == 0 : return False
# 2. ์ธ์ ๋
ธ๋ ์ํ
for [i,j] in [[x+1,y],[x,y+1],[x-1,y],[x,y-1]] :
if 0 <= i <= n-1 and 0 <= j <= m-1 :
if map_[i][j] == 1 and not visited[i][j]:
dfs(i,j,visited)
elif map_[i][j] == 0 :
visited[i][j] = 1
return True
cnt = 0
for i in range(n) :
for j in range(m) :
if not visited[i][j] :
bool_ = dfs(i,j,visited)
if bool_ : cnt+=1
cnt_lst.append(cnt)
print(*cnt_lst,sep='\n')
๋ฉ๋ชจ๋ฆฌ | ์๊ฐ | ์ธ์ด | ์ฝ๋๊ธธ์ด |
32148KB | 404ms | Python 3 | 1004B |
๊ณผ์ )
์ฒ์ ์ ์ถํ์ ๋ ๋ฐํ์์๋ฌ(recursion error)๊ฐ ๋ฐ์ํ์ฌ
๋งจ ์์ ๋์ค์ ์ถ๊ฐํด์ฃผ์๋ค
import sys
sys.setrecursionlimit(100000000)
728x90
๋ฐ์ํ
'๋ฐฑ์ค & ํ๋ก๊ทธ๋๋จธ์ค > DFS & BFS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํ๋ก๊ทธ๋๋จธ์ค] DFS/BFS level2 ํ๊ฒ๋๋ฒ (0) | 2022.03.24 |
---|---|
[๋ฐฑ์ค 1012] [dfs/bfs] ์ ๊ธฐ๋ ๋ฐฐ์ถ (0) | 2021.04.29 |
[๋ฐฑ์ค 2667] [dfs/bfs] ๋จ์ง๋ฒํธ๋ถ์ด๊ธฐ (0) | 2021.04.23 |
[๋ฐฑ์ค 2178] [dfs/bfs] ๋ฏธ๋กํ์ (0) | 2021.04.23 |
[๋ฐฑ์ค 1260] [dfs/bfs] BFS์ DFS โ (0) | 2021.04.23 |
[๋ฐฑ์ค 2606] [dfs/bfs] ๋ฐ์ด๋ฌ์ค (0) | 2021.04.22 |
[๋ฐฑ์ค 2331] [dfs] ๋ฐ๋ณต์์ด (0) | 2021.04.22 |