Skip to content

Commit a503693

Browse files
committed
topological sorting
1 parent a5a25e1 commit a503693

File tree

3 files changed

+45
-3
lines changed

3 files changed

+45
-3
lines changed

Diff for: src/graph/DAG和拓扑排序.md

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
### 以上代码使用了**拓扑排序**的方法来判断是否可以完成所有课程的学习。
2+
下面是代码的具体解释:
3+
1. 首先,我们创建了一个长度为 numCourses 的数组 indegree,用来记录每门课程的入度,即有多少门课程需要先修这门课程。同时,创建了一个哈希表 graph,用来记录每门课程的后继课程。
4+
5+
2. 接着,我们遍历 prerequisites 数组,对每对 [ai, bi],将 ai 的入度加一,并将 ai 加入 bi 的后继课程列表中。
6+
7+
3. 然后,我们初始化一个队列 queue,并将所有入度为 0 的课程加入队列中。
8+
9+
4. 在接下来的循环中,我们不断从队列中取出课程,遍历其后继课程,更新后继课程的入度。如果某门后继课程的入度减为 0,则将其加入队列中。
10+
11+
5. 最后,我们判断是否所有课程的入度都为 0。如果是,则表示可以完成所有课程的学习,返回 True;否则返回 False。
12+
13+
通过这种方法,我们可以有效地判断是否可以完成所有课程的学习,避免了死循环或者无法完成所有课程学习的情况。

Diff for: src/graph/course.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from collections import defaultdict, deque
2+
3+
def canFinish(numCourses, prerequisites):
4+
indegree = [0] * numCourses
5+
graph = defaultdict(list)
6+
7+
for course, pre in prerequisites:
8+
indegree[course] += 1
9+
graph[pre].append(course)
10+
11+
queue = deque()
12+
for i in range(numCourses):
13+
if indegree[i] == 0:
14+
queue.append(i)
15+
16+
while queue:
17+
course = queue.popleft()
18+
for next_course in graph[course]:
19+
indegree[next_course] -= 1
20+
if indegree[next_course] == 0:
21+
queue.append(next_course)
22+
23+
return all(indegree[i] == 0 for i in range(numCourses))
24+
25+
# 示例
26+
## [a , b] ,可以表示为 b -> a
27+
print(canFinish(2, [[1, 0]])) # 返回 True
28+
print(canFinish(2, [[1, 0], [0, 1]])) # 返回 False

Diff for: src/graph/test.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import heapq
22

3-
43
def dijkstra(graph , start_node):
5-
distances = { node : float('inf') for node in graph}
4+
distances = {node : float('inf') for node in graph}
65
distances[start_node] = 0
76
pq = [( 0 , start_node)]
7+
88
while pq:
99
current_distance , current_node = heapq.heappop(pq)
1010
if current_distance > distances[current_node]:
@@ -14,12 +14,13 @@ def dijkstra(graph , start_node):
1414
if distance < distances[neighbour]:
1515
distances[neighbour] = distance
1616
heapq.heappush(pq , (distance , neighbour))
17-
17+
1818
return distances
1919

2020

2121

2222

23+
2324
graph = {
2425
'A': {'B': 1, 'C': 4},
2526
'B': {'A': 1, 'C': 2, 'D': 5},

0 commit comments

Comments
 (0)