There are a total of n courses you have to take, labeled from 0
to n-1
.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
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.
Note:
- The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
- You may assume that there are no duplicate edges in the input prerequisites.
把所有入度为0的节点找出来,每轮刷新所有节点入度的值,直到所有节点都刷过,如果没有刷过就是存在环
class Node:
def __init__(self, index):
self.index = index
self.nexts = set()
class Solution:
def get_zeros(self, numCourses, in_degree, checked):
zeros = []
for i in range(numCourses):
if in_degree[i] == 0 and checked[i] == 0:
zeros.append(i)
checked[i] = 1
return zeros
def canFinish(self, numCourses, prerequisites):
nodes = [Node(i) for i in range(numCourses)]
in_degree = [0 for i in range(numCourses)]
checked = [0 for i in range(numCourses)]
for edge in prerequisites:
nodes[edge[1]].nexts.add(edge[0])
in_degree[edge[0]]+=1
zeros = self.get_zeros(numCourses, in_degree, checked)
while (zeros and sum(checked) < numCourses):
for cur in zeros:
for next in nodes[cur].nexts:
in_degree[next] -= 1
zeros = self.get_zeros(numCourses, in_degree, checked)
return sum(checked) == numCourses
s = Solution()
res = s.canFinish(8,[[1,0],[2,6],[1,7],[6,4],[7,0],[0,5]])
print(res)
------------------------------------------------------------------
There are a total of n courses you have to take, labeled from 0
to n-1
.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
Example 1:
Input: 2, [[1,0]] Output:[0,1]
Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is[0,1] .
Example 2:
Input: 4, [[1,0],[2,0],[3,1],[3,2]] Output:[0,1,2,3] or [0,2,1,3]
Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is[0,1,2,3]
. Another correct ordering is[0,2,1,3] .
Note:
- The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
- You may assume that there are no duplicate edges in the input prerequisites.
----------------------------------------------------------------------------------------------------------------
回想自己之前写的codes非常naive,get_zeros又浪费了O(n)的复杂度,可以把入度为0的扔到栈里,仿照DFS的写法:
class Solution:
def findOrder(self, numCourses: int, prerequisites):
dic, in_degree = {i:[] for i in range(numCourses)}, [0 for i in range(numCourses)]
for pre in prerequisites:
to, frm = pre[0], pre[1]
dic[frm].append(to)
in_degree[to] += 1
in_degree_sta = [i for i in range(numCourses)[::-1] if in_degree[i] == 0]
res = []
while (in_degree_sta):
in_degree_0 = in_degree_sta.pop()
res.append(in_degree_0)
while (dic[in_degree_0]):
to = dic[in_degree_0].pop()
in_degree[to] -= 1
if (in_degree[to] == 0):
in_degree_sta.append(to)
return res if len(res) == numCourses else []
-------------------------------------------------------------------------------------
In a directed graph, we start at some node and every turn, walk along a directed edge of the graph. If we reach a node that is terminal (that is, it has no outgoing directed edges), we stop.
Now, say our starting node is eventually safe if and only if we must eventually walk to a terminal node. More specifically, there exists a natural number K
so that for any choice of where to walk, we must have stopped at a terminal node in less than K
steps.
Which nodes are eventually safe? Return them as an array in sorted order.
The directed graph has N
nodes with labels 0, 1, ..., N-1
, where N
is the length of graph
. The graph is given in the following form: graph[i]
is a list of labels j
such that (i, j)
is a directed edge of the graph.
Example:
Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]
Here is a diagram of the above graph.
Note:
graph
will have length at most10000
.- The number of edges in the graph will not exceed
32000
. - Each
graph[i]
will be a sorted list of different integers, chosen within the range[0, graph.length - 1]
.
------------------------------------------------------------------
反应慢,入度和出度开始没有想明白。。。
class Solution:
def eventualSafeNodes(self, graph):
n = len(graph)
out_degree, res = [len(graph[i]) for i in range(n)], []
frm_graph = [[] for i in range(n)]
for frm in range(n):
for to in graph[frm]:
frm_graph[to].append(frm)
out_degree_0 = [i for i in range(n) if (out_degree[i] == 0)]
while (out_degree_0):
n0 = out_degree_0.pop()
res.append(n0)
for frm in frm_graph[n0]:
out_degree[frm] -= 1
if (out_degree[frm] == 0):
out_degree_0.append(frm)
res.sort()
return res
---------------------------------------------------------------------
There are N
courses, labelled from 1 to N
.
We are given relations[i] = [X, Y]
, representing a prerequisite relationship between course X
and course Y
: course X
has to be studied before course Y
.
In one semester you can study any number of courses as long as you have studied all the prerequisites for the course you are studying.
Return the minimum number of semesters needed to study all courses. If there is no way to study all the courses, return -1
.
Example 1:
Input: N = 3, relations = [[1,3],[2,3]] Output: 2 Explanation: In the first semester, courses 1 and 2 are studied. In the second semester, course 3 is studied.
Example 2:
Input: N = 3, relations = [[1,2],[2,3],[3,1]] Output: -1 Explanation: No course can be studied because they depend on each other.
Note:
1 <= N <= 5000
1 <= relations.length <= 5000
relations[i][0] != relations[i][1]
- There are no repeated relations in the input.
------------------------------------------------------------------------------
BFS的方式也可以搞:
class Solution:
def minimumSemesters(self, N: int, relations: List[List[int]]) -> int:
nxt_arr = [[] for i in range(N+1)]
in_degree = [0 for i in range(N+1)]
for rel in relations:
frm,to = rel[0],rel[1]
in_degree[to] += 1
nxt_arr[frm].append(to)
in_degree_0 = [i for i in range(1,N+1) if in_degree[i] == 0]
layers = [in_degree_0, []]
c,n,step,total = 0,1,0,len(in_degree_0)
while (layers[c]):
step += 1
for node in layers[c]:
for nxt in nxt_arr[node]:
in_degree[nxt] -= 1
if (in_degree[nxt] == 0):
layers[n].append(nxt)
total += 1
layers[c].clear()
c,n = n,c
return step if total == N else -1