207. Course Schedule
題目解釋:總共有n種的課你需要去上,這些課標號從0到n-1。你上某些課程之前需要有一些先修課程,如你想要參加課程0,那麼你必須先學習完課程1,這個可以採用一個配對來表示:[0,1]。
給出總的課程數以及先修課程匹配對,判斷一下,你是否能修完所有的課程?
Example 1:
Input: 2, [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2:
Input: 2, [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should
also have finished course 1. So it is impossible.
解釋:在給出的兩個課程對中,課程0和課程1互爲先修課程,所以對於你來說,是不可能修完所有的課程的。
題目分析:在這裏我們先分析出pair的特點,以[0,1]舉例:
這是兩門課程,你想要修習課程0,那麼你就必須先學習課程1,即是1->0
看到這樣的表示,我們應該是有一些感觸的。這種表示方式是不是和我們學習的有向圖很類似,在本題中,如果所有的結點都組合起來能夠圍成一個有向無環圖,那麼我們就是能夠修習完所有的課程。這樣我們的問題就變成了查看給定的圖是否是是無環圖。那麼我們首先是需要構建圖,然後根據拓撲排序來解決。
PS:本題講道理來說,還是很難的,因爲我們需要自己構建圖,然後來判斷構建的圖是否是有環,但是難着難着感覺我們就習慣了,多看兩遍,然後有了手感,寫一下,就會發現整體來說,我們還是能解決的,索然過程還是比較痛苦的,但是這也是在代表着我們在進步,不是麼?(手動打雞血......)
class Solution(object):
def canFinish(self, numCourses, prerequisites):
"""
採用BFS
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: bool
"""
graph=collections.defaultdict(list)
indegrees=collections.defaultdict(int)
# 組建一幅圖,其中u是相當於結點的第一個點,v是結點的第二條點,這就是graph代表的意義
# 這裏是先修課程,如[1,0]代表要修1,就要先修0,所以理解好入度和出度的關係,indegrees代表入度
# 初始化建圖
for u,v in prerequisites:
graph[v].append(u)
indegrees[u]+=1
for i in range(numCourses):
zero_degree=False
for j in range(numCourses):# 若某個結點的入度爲0
if indegrees[j]==0:
zero_degree=True
break
if not zero_degree:
return False
# 結點j的入度減去1,同時在圖中j指向的結點的入度減去1
indegrees[j]-=1
for node in graph[j]:
indegrees[node]-=1
return True
另外,用了BFS,我們同樣可以嘗試DFS。
def canFinish1(self, N, prerequisites):
"""
:type N,: int
:type prerequisites: List[List[int]]
:rtype: bool
"""
graph = collections.defaultdict(list)
for u, v in prerequisites:
graph[u].append(v)
# 0 = Unknown, 1 = visiting, 2 = visited
visited = [0] * N
for i in range(N):
if not self.dfs(graph, visited, i):
return False
return True
def dfs(self, graph, visited, i):
if visited[i] == 1:
return False
if visited[i] == 2:
return True
visited[i] = 1
for j in graph[i]:
if not self.dfs(graph, visited, j):
return False
visited[i] = 2
return True