https://www.acmicpc.net/problem/1012
1012번: 유기농 배추
차세대 영농인 한나는 강원도 고랭지에서 유기농 배추를 재배하기로 하였다. 농약을 쓰지 않고 배추를 재배하려면 배추를 해충으로부터 보호하는 것이 중요하기 때문에, 한나는 해충 방지에
www.acmicpc.net
import sys
input = sys.stdin.readline
def main():
def dfs(i,j):
nonlocal graph
discovered = [[i,j]]
while discovered:
pos = discovered.pop()
graph[pos[0]][pos[1]] = 0
next_pos = [[pos[0]+1,pos[1]],[pos[0]-1,pos[1]],[pos[0],pos[1]+1],[pos[0],pos[1]-1]]
for np in next_pos:
if 0<= np[0] < N and 0<= np[1] < M and graph[np[0]][np[1]] == 1:
discovered.append(np)
return
test_case = int(input().strip())
for i in range(test_case):
counters = 0
M,N,K = map(int,input().split())
graph = [[0] * M for _ in range(N)]
pos = [list(map(int, input().split())) for _ in range(K)]
for i in pos:
graph[i[1]][i[0]] = 1
for i in range(N):
for j in range(M):
if graph[i][j] == 0:
continue
dfs(i,j)
counters += 1
print(counters)
return
main()
2차원 리스트를 돌면서 인접해있는 집단이 몇개있지 구하는 쉬운 그래프 문제였다. 백준은 재귀함수의 깊이 제한이 있어서 dfs를 재귀로 구현했다가 다시 while 문으로 바꿔주었다.
'백준 문제 풀이 및 피드백' 카테고리의 다른 글
| 2023.01.17 팩토리얼 0의 개수[파이썬] (1) | 2023.01.17 |
|---|---|
| 2023.01.17 1로 만들기 백준 (0) | 2023.01.17 |
| 2023.01.16 백준 DFS와 BFS (0) | 2023.01.16 |
| 2023.01.15 반복수열 백준(Python) (0) | 2023.01.15 |
| 2023.01.15 미로탐색 백준 (0) | 2023.01.15 |