描述
给定一个有向图,图节点的拓扑排序被定义为:
- 对于每条有向边A--> B,则A必须排在B之前
- 拓扑排序的第一个节点可以是任何在图中没有其他节点指向它的节点
找到给定图的任一拓扑排序
你可以假设图中至少存在一种拓扑排序
您在真实的面试中是否遇到过这个题? 是
说明
Learn more about representation of graphs
样例
对于下列图:
这个图的拓扑排序可能是:
[0, 1, 2, 3, 4, 5]
或者
[0, 2, 3, 1, 5, 4]
或者
....
挑战
能否分别用BFS和DFS完成?
先放目前时间排名第一的算法,充分的利用了字典和集合
""" Definition for a Directed graph node class DirectedGraphNode: def __init__(self, x): self.label = x self.neighbors = [] """ class Solution: """ @param: graph: A list of Directed graph node @return: Any topological order for the given graph. """ def topSort(self, graph): # write your code here count = {graph[i]: 0 for i in range(len(graph))} for node in graph: for neighbor in node.neighbors: count[neighbor] += 1 result = [] s = set() for k, v in count.items(): if v == 0: s.add(k) result.append(k) for i in s: count.pop(i) while len(s) > 0: newS = set() for i in s: for neighbor in i.neighbors: count[neighbor] -= 1 if count[neighbor] == 0: count.pop(neighbor) result.append(neighbor) newS.add(neighbor) s = newS return result
DFS解法:
""" Definition for a Directed graph node class DirectedGraphNode: def __init__(self, x): self.label = x self.neighbors = [] """ class Solution: def dfs(self, i, countrd, ans): ans.append(i) countrd[i] -= 1 for j in i.neighbors: countrd[j] -= 1 if countrd[j] == 0: self.dfs(j, countrd, ans) """ @param: graph: A list of Directed graph node @return: Any topological order for the given graph. """ def topSort(self, graph): # write your code here countrd = {} for x in graph: countrd[x] = 0 for i in graph: for j in i.neighbors: countrd[j] = countrd[j] + 1 ans = [] for i in graph: if countrd[i] == 0: self.dfs(i, countrd, ans) return ans
BFS解法:
class Solution: """ @param: graph: A list of Directed graph node @return: Any topological order for the given graph. """ def topSort(self, graph): # define indegree with dict indegree = dict((i, 0) for i in graph) for i in graph: for j in i.neighbors: indegree[j] += 1 # define queue and put the 0 degree nodes import queue q = queue() for i in graph: if indegree[i] == 0: q.put(i) # result and bfs result = [] while not q.empty(): node = q.get() result.append(node) for j in node.neighbors: indegree[j] -= 1 if indegree[j] == 0: q.put(j) return result