程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Leetcode problem solution (0210): curriculum II (Python)

編輯:Python


subject :​ ​ The original title is link ​​( secondary )

label : chart 、 A topological sort 、 Breadth first search 、 Depth-first search

solution

Time complexity

Spatial complexity

Execution time

Ans 1 (Python)

O ( N )

O ( N )

84ms (12.88%)

Ans 2 (Python)

Ans 3 (Python)

Solution 1 :

def build_graph(edges):

graph_in = collections.defaultdict(set)
graph_out = collections.defaultdict(set)
for edge in edges:
graph_in[edge[1]].add(edge[0])
graph_out[edge[0]].add(edge[1])
return graph_out, graph_in


def topo(graph_in, graph_out):
count = {} # Node incident edge statistics
queue = [] # The current incident edge is 0 List of nodes

# Count the incident edges of all nodes
for node in graph_in:
count[node] = len(graph_in[node])
for node in graph_out:
if node not in count:
count[node] = 0
queue.append(node)

# A topological sort
order = []
while queue:
node = queue.pop()
order.append(node)
for next in graph_out[node]:
count[next] -= 1
if count[next] == 0:
queue.append(next)

return order


class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
# Generating adjacency list structure of edges in digraph
graph_in, graph_out = build_graph(prerequisites)

# A topological sort
order = topo(graph_in, graph_out)
order_set = set(order)

for node in graph_in:
if node not in order:
return []

for i in range(numCourses):
if i not in order_set:
order.append(i)

return order
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.




  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved