문제풀이/백준(Boj) 문제풀이

[백준][DFS] 1012. 유기농 배추 (파이썬/Python)

얄루몬 2021. 12. 2. 17:33

<오답>

import sys
sys.setrecursionlimit(10**6) #재귀함수 호출범위를 늘린다.

def DFS(x,y):
    
    #범위를 벗어나면 False
    if x >= m or x < 0 or y >= n or y < 0:
        return False
    
    if graph[x][y] == 1:
        graph[x][y] = 0
        DFS(x,y-1)
        DFS(x,y+1)
        DFS(x-1,y)
        DFS(x+1,y)
        return True
    return False

result = []
TestCase = int(input())
for _ in range(TestCase):
    m,n,k = map(int,input().split())
    graph = [[0]*m for _ in range(n)]
    cnt = 0
    
    for _ in range(k):
        y,x = map(int,input().split())
        graph[x][y] = 1
    
    for i in range(n):
        for j in range(m):
            if DFS(i,j) == True:
                cnt += 1
    result.append(cnt)
for i in result:
    print(i)

#런타임 에러가 났다. 다른 분의 코드를 보고 수정해야 할 것 같다. 

 

 

<정답>

from sys import stdin
import sys
sys.setrecursionlimit(10**9)

t = int(input()) # 테스트케이스 2개
result_list = []

def make_graph(m, n, k):
    graph = [[0] * m for _ in range(n)]
    for _ in range(k):
        x, y = map(int, stdin.readline().split())
        graph[y][x] = 1
    return graph


def dfs(y, x):
    if x <= -1 or x >= m or y <= -1 or y >= n:
        return False

    if graph[y][x] == 1:
        graph[y][x] = 0
        dfs(y-1, x)
        dfs(y+1, x)
        dfs(y, x-1)
        dfs(y, x+1)
        return True
    return False


for _ in range(t):
    result = 0
    m, n, k = map(int, stdin.readline().split())
    graph = make_graph(m, n, k)
    for i in range(n):
        for j in range(m):
            if dfs(i,j) == True:
                result += 1
    result_list.append(result)

print(*result_list, sep='\n')

📌참고: https://reliablecho-programming.tistory.com/29?category=951029