HardNo. 2959
Number of Possible Sets of Closing Branches — LeetCode 2959 Python Solution
- Pattern
- Heap / Priority Queue
- Topics
- Bit Manipulation, Graph, Enumeration, Shortest Path, Heap (Priority Queue)
- Reading time
- 5 min
- Source
- leetcode.com
The problem
There is a company with n branches across the country, some of which are connected by roads. Initially, all branches are reachable from each other by traveling some roads.
Example
- Input
- n = 3, maxDistance = 5, roads = [[0,1,2],[1,2,10],[0,2,10]]
- Output
- 5
- Explanation
- The possible sets of closing branches are:
Python solution
class Solution:
def numberOfSets(self, n: int, maxDistance: int, roads: List[List[int]]) -> int:
ans = 0
for mask in range(1 << n):
g = [[inf] * n for _ in range(n)]
for u, v, w in roads:
if mask >> u & 1 and mask >> v & 1:
g[u][v] = min(g[u][v], w)
g[v][u] = min(g[v][u], w)
for k in range(n):
if mask >> k & 1:
g[k][k] = 0
for i in range(n):
for j in range(n):
# g[i][j] = min(g[i][j], g[i][k] + g[k][j])
if g[i][k] + g[k][j] < g[i][j]:
g[i][j] = g[i][k] + g[k][j]
if all(
g[i][j] <= maxDistance
for i in range(n)
for j in range(n)
if mask >> i & 1 and mask >> j & 1
):
ans += 1
return ansComplexity
- Time
- O(2n × (n3 + m))
- Space · auxiliary
- O(n2)
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2959. Number of Possible Sets of Closing Branches is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0743 | Network Delay Time | Medium |
| 0882 | Reachable Nodes In Subdivided Graph | Hard |
| 1368 | Minimum Cost to Make at Least One Valid Path in a Grid | Hard |
| 1514 | Path with Maximum Probability | Medium |
| 2290 | Minimum Obstacle Removal to Reach Corner | Hard |
| 2577 | Minimum Time to Visit a Cell In a Grid | Hard |
Frequently asked questions
- How hard is LeetCode 2959. Number of Possible Sets of Closing Branches?
LeetCode 2959. Number of Possible Sets of Closing Branches is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2959. Number of Possible Sets of Closing Branches?
The Python solution on this page runs in O(2n × (n3 + m)).
- What is the space complexity of LeetCode 2959. Number of Possible Sets of Closing Branches?
The Python solution on this page uses O(n2) auxiliary space.
- What topics does LeetCode 2959. Number of Possible Sets of Closing Branches cover?
LeetCode 2959. Number of Possible Sets of Closing Branches is tagged Bit Manipulation, Graph, Enumeration, Shortest Path and Heap (Priority Queue) on LeetCode.