Skip to content

Commit dadf405

Browse files
committed
feat: add course schedule solution
1 parent 5746266 commit dadf405

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

โ€Žcourse-schedule/mangodm-web.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
6+
"""
7+
- Idea: ๊ฐ ๊ณผ๋ชฉ์˜ ์„ ํ–‰ ๊ณผ๋ชฉ์— ์‚ฌ์ดํด์ด ์กด์žฌํ•˜๋Š”์ง€ DFS๋กœ ํƒ์ƒ‰ํ•œ๋‹ค.
8+
ํ•˜๋‚˜๋ผ๋„ ์‚ฌ์ดํด์ด ์กด์žฌํ•œ๋‹ค๋ฉด, ๋ชจ๋“  ๊ณผ๋ชฉ์„ ์ˆ˜๊ฐ•ํ•  ์ˆ˜ ์—†๋‹ค๋Š” ์˜๋ฏธ๋‹ค.
9+
- Time Complexity: O(v + e). v์™€ e๋Š” ๊ฐ๊ฐ ๊ณผ๋ชฉ์˜ ์ˆ˜, e๋Š” ์„ ํ–‰ ๊ด€๊ณ„(๊ณผ๋ชฉ => ์„ ํ–‰ ๊ณผ๋ชฉ)์˜ ์ˆ˜๋‹ค.
10+
๋ชจ๋“  ๊ณผ๋ชฉ๊ณผ ๊ทธ ๊ณผ๋ชฉ์˜ ์„ ํ–‰ ๊ณผ๋ชฉ์„ ํƒ์ƒ‰ํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ ๋…ธ๋“œ์™€ ์—ฃ์ง€์— ๋Œ€ํ•ด ํ•œ๋ฒˆ์”ฉ ๋ฐฉ๋ฌธํ•ด์•ผ ํ•œ๋‹ค.
11+
- Space Complexity: O(v). v๋Š” ๊ณผ๋ชฉ์˜ ์ˆ˜๋‹ค.
12+
๊ฐ ๊ณผ๋ชฉ์— ๋Œ€ํ•ด์„œ ๊ทธ๋ž˜ํ”„(์„ ํ–‰ ๊ด€๊ณ„)๋ฅผ ์ €์žฅํ•˜๊ณ , ์žฌ๊ท€ ํ˜ธ์ถœ ์Šคํƒ์— ์˜ํ•ด ๊ณต๊ฐ„์ด ์‚ฌ์šฉ๋œ๋‹ค.
13+
"""
14+
15+
graph = {i: [] for i in range(numCourses)}
16+
17+
for course, prerequisite in prerequisites:
18+
graph[course].append(prerequisite)
19+
20+
visited = set()
21+
22+
def DFS(course):
23+
if course in visited:
24+
return False
25+
if graph[course] == []:
26+
return True
27+
28+
visited.add(course)
29+
for prerequisite in graph[course]:
30+
if not DFS(prerequisite):
31+
return False
32+
33+
visited.remove(course)
34+
graph[course] = []
35+
36+
return True
37+
38+
for course in range(numCourses):
39+
if not DFS(course):
40+
return False
41+
42+
return True

0 commit comments

Comments
ย (0)