Back to course home
0% completed
Vote For New Content
a better solution with explanation
Mohammed Dh Abbas
Jun 10, 2024
from collections import deque class Solution: # build a unidrictional graph def build_graph(self, nodes, edges): graph, indegree = {}, {} for i in range(nodes): graph[i] = [] indegree[i] = 0 for node1, node2 in edges: graph[node1].append(node2) graph[node2].append(node1) indegree[node1] += 1 indegree[node2] += 1 return(graph, indegree) def findTrees(self, nodes, edges): if nodes == 1: return [0] graph, indegree = self.build_graph(nodes, edges) q = deque([x for x in indegree if indegree[x] == 1]) result = [] # topological ordering can be done on unidirectional graph too # for that we should do indegree[neighbor] == 1 as edge nodes are linked # topological finds the center of graph in unidirectional graph # e.g. A -- B -- C --- D # topological ordering will start with A and D as edge nodes and goes to the center [B,C] # the center can have one or more nodes. so we go level by level "its a BFS at the end" # center nodes will give you the shortest trees for sure! while q: result.clear() for _ in range(len(q)): # for each level node = q.popleft() result.append(node) # the result contains the level nodes = last level for neighbor in graph[node]: indegree[neighbor] -= 1 if indegree[neighbor] == 1: q.append(neighbor) return result
1
0
Comments
Comments
On this page