백준 풀이
[백준/BOJ] - 1325번 python 풀이 - DFS
반오십 코린이
2023. 3. 6. 13:58
728x90
1. 시간 초과가 나지만 근본 dfs 방식으로 로직만 이해하고 싶어 포스팅
2. 함수 호출할 때 방문 함수를 초기화 시키는 부분과 cnt 값을 1로 초기화 시키는 부분 주목
3. 2차원 배열에 입력값을 삽입하는 부분에서 a,b를 반대로 넣는 부분은
한 번에 가장 많은 컴퓨터를 해킹할 수 있는 컴퓨터에서부터 탐색을 시작하게 끔 하기 위해서 이다.
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
n,m = map(int,input().split())
arr = [[] for _ in range(n+1)]
cnt = 0
for _ in range(m):
a,b = map(int,input().split())
arr[b].append(a)
def dfs(i):
global cnt
visit[i] = True
for item in arr[i]:
if not visit[item]:
cnt+=1
dfs(item)
max_cnt = -1
for i in range(1, n+1):
visit = [False]*(n+1)
cnt = 1
dfs(i)
if cnt > max_cnt:
max_cnt = cnt
res = set([])
res.add(i)
elif cnt == max_cnt:
res.add(i)
print(*res)
728x90