Minimum Fuel Cost to Report to the Capital — LeetCode 2477 Python Solution
- Problem
- #2477
- Pattern
- Tree Traversal
- Reading time
- 4 min
- Source
- leetcode.com
The problem
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of n cities numbered from 0 to n - 1 and exactly n - 1 roads. The capital city is city 0.
Example
- Input
- roads = [[0,1],[0,2],[0,3]], seats = 5
- Output
- 3
- Explanation
- - Representative1 goes directly to the capital with 1 liter of fuel.
Python solution
class Solution:
def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int:
def dfs(a: int, fa: int) -> int:
nonlocal ans
sz = 1
for b in g[a]:
if b != fa:
t = dfs(b, a)
ans += ceil(t / seats)
sz += t
return sz
g = defaultdict(list)
for a, b in roads:
g[a].append(b)
g[b].append(a)
ans = 0
dfs(0, -1)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2477. Minimum Fuel Cost to Report to the Capital is filed here because LeetCode tags it Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2477. Minimum Fuel Cost to Report to the Capital?
- LeetCode 2477. Minimum Fuel Cost to Report to the Capital is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2477. Minimum Fuel Cost to Report to the Capital?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2477. Minimum Fuel Cost to Report to the Capital?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2477. Minimum Fuel Cost to Report to the Capital cover?
- LeetCode 2477. Minimum Fuel Cost to Report to the Capital is tagged Tree, Depth-First Search, Breadth-First Search and Graph on LeetCode.