[백준] 10891번: Cactus? Not cactus?

whitehousechef·2023년 10월 6일
0

https://www.acmicpc.net/problem/10891

initial

revisited jan 13th, it works for example but doesnt pass at 1%. Impt that when we meet a visited node, we flag it and return cuz we dont want to keep traverssing to other nodes once we have found a cycle.

import sys
input = sys.stdin.readline

n , m = map(int,input().split())
visited = [False for _ in range(n+1)]
graph = defaultdict(list)

for _ in range(m):
    a,b = map(int,input().split())
    graph[a].append(b)
flag = False

def dfs(i):
    global flag
    visited[i]=True
    for node in graph[i]:
        if not visited[node]:
            dfs(node)
        else:
            if not flag:
                flag=True
                break
            else:
                print("Not cactus")
                exit()

for i in range(1,n+1):
    if not visited[i]:
        dfs(i)

if flag==True:
    print("Cactus")

0개의 댓글