- Reference
graph
- ๋ฐฑ์ค: List
- LeetCode: defaultdict(list)
Solution
import collections
from typing import List
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
graph = collections.defaultdict(list)
for x, y in prerequisites:
graph[x].append(y)
traced, visited = set(), set()
def dfs(index) -> bool:
# ์ํ ๊ตฌ์กฐ์ผ ๋
if index in traced:
return False
# ์ด๋ฏธ ๋ฐฉ๋ฌธํ๋ ๋
ธ๋์ผ ๋
if index in visited:
return True
traced.add(index)
for y in graph[index]:
# ์ํ ๊ตฌ์กฐ์ผ ๋
if not dfs(y):
return False
# ํ์ ์ข
๋ฃ ํ -> ์ํ, ๋ฐฉ๋ฌธ ๋
ธ๋ ๊ฐ๊ฐ ์ญ์ , ์ถ๊ฐ
traced.remove(index)
visited.add(index)
return True
for x in list(graph):
if not dfs(x):
return False
return True
Leave a comment