Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from Queue import PriorityQueue
- def peekQueue(queue):
- result = queue.get()
- queue.put(result)
- return result
- def numMinSpanningTrees(edges):
- if edges is None or not edges:
- return 0
- vertex_set = set()
- pq = PriorityQueue()
- for v1, v2, w in edges:
- pq.put((w, v1, v2))
- vertex_set.add(v1)
- vertex_set.add(v2)
- tree_set = range(len(vertex_set))
- def findRoot(v, tree_set):
- root = v
- while tree_set[root] != root:
- root = tree_set[root]
- return root
- def numMst(tree_set, num_trees, queue):
- if queue.empty():
- if num_trees == 1:
- print temp_result
- return 1
- return 0
- next_edges = [queue.get()]
- if not queue.empty():
- while not queue.empty() and peekQueue(queue)[0] == next_edges[0][0]:
- next_edges.append(queue.get())
- result = 0
- found_valid_edge = False
- for i in range(len(next_edges)):
- w, v1, v2 = next_edges[i]
- v1_root = findRoot(v1, tree_set)
- v2_root = findRoot(v2, tree_set)
- if v1_root != v2_root:
- found_valid_edge = True
- if num_trees == 2:
- result += 1
- else:
- tree_set[v1_root] = v2_root
- for j in range(i + 1, len(next_edges)):
- queue.put(next_edges[j])
- result += numMst(tree_set, num_trees - 1, queue)
- for j in range(i + 1, len(next_edges)):
- queue.get()
- tree_set[v1_root] = v1_root
- if not found_valid_edge:
- result = numMst(tree_set, num_trees, queue)
- for edge in next_edges:
- queue.put(edge)
- return result
- return numMst(tree_set, len(tree_set), pq)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement