Tree Span and Grid Escape: Two Graph Queries in One Call
Trees & GraphsAuto-graded · 21 test casesLast updated
Compute a tree's longest path in edges and the shortest 4-directional route through a grid with obstacles, returning both results together.
You are given two independent graph tasks, and your function must answer both and return the results together.
Part 1: Widest reach of a tree
There is a tree with n nodes labeled 1 through n. It is connected, undirected, and has no cycles. The tree is described by edges, a list of n - 1 pairs [u, v], each meaning an undirected connection between nodes u and v. Every connection counts as length 1.
Find the largest possible distance between any two nodes, where distance is the number of edges on the unique simple path joining them. A tree with a single node has this value 0.
Part 2: Escaping a square grid
There is a square grid with m rows and m columns, where m = len(grid). A cell holding 0 is open and a cell holding 1 is blocked.
You begin at the top-left cell (0, 0) and want to arrive at the bottom-right cell (m - 1, m - 1). In each step you move to one of the four orthogonally adjacent cells (up, down, left, right). You may only enter cells that lie inside the grid and are open.
Find the minimum number of steps needed. Return -1 if the destination cannot be reached, which includes the case where the start cell or the destination cell is blocked. If m = 1 and the single cell is open, the answer is 0.
Output
Return a list of two integers [tree_result, grid_result]:
tree_resultis the longest distance, in edges, between two nodes of the tree.grid_resultis the fewest steps from the top-left to the bottom-right cell, or-1if it is impossible.
Constraints
1 <= n <= 10^5edgeshas exactlyn - 1entries and forms a valid tree.- The grid is square with side length up to a few hundred; every entry is
0or1. - Your solution should run in time linear in the size of each input (
O(n)for the tree,O(m^2)for the grid). - If the grid is empty, treat the grid result as
-1.
Examples
Example 1
Input: tree_span_and_grid_escape(5, [[1, 2], [2, 3], [3, 4], [2, 5]], [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])
Output: [3, 8]
Example 2
Input: tree_span_and_grid_escape(1, [], [[0]])
Output: [0, 0]
Example 3
Input: tree_span_and_grid_escape(4, [[1, 2], [1, 3], [3, 4]], [[0, 1, 0, 0], [0, 1, 0, 1], [0, 0, 0, 1], [1, 1, 0, 0]])
Output: [3, 6]
Hints
Hint 1
For the tree, pick any node and find the node farthest from it. Then think about what happens if you search again from that farthest node.
Hint 2
Every move in the grid costs the same, so a breadth-first search visits cells in order of increasing distance. Mark a cell as seen when you add it to the queue.
Hint 3
Avoid deep recursion on a tree with 100,000 nodes: use an iterative BFS with a queue. Handle the edge cases n = 1 and a blocked start or end cell separately.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The two parts are independent, and both are solved with breadth-first search.
Tree: longest path (diameter)
- Build an adjacency list from
edges. - Run a BFS from any node (node 1) and take the node
awith the largest distance. - Run a second BFS from
a. The largest distance found is the answer.
If n = 1 there are no edges and the answer is 0.
Why it works: in a tree, the node farthest from any starting node is always one end of some longest path. Intuitively, if the start's farthest node were not such an endpoint, you could swap in an endpoint of a true longest path and get a strictly longer or equal route, which contradicts the choice of farthest node. Once we stand on one endpoint, the farthest node from it is the other endpoint, so the second BFS yields the exact diameter.
An iterative BFS is used so that a path-shaped tree with 100,000 nodes does not overflow the recursion stack.
Grid: shortest path
- If the grid is empty, or the start or destination is blocked, return
-1. - Run BFS from
(0, 0)over open cells, recording the distance of each cell when it is first enqueued. - The distance stored at
(m - 1, m - 1)is the answer, or-1if it was never reached.
Why it works: every step costs 1, so BFS discovers cells layer by layer in increasing distance order. The first time a cell is discovered it is reached by a shortest route. Marking cells when they are enqueued ensures each cell is queued only once. A 1x1 open grid gives 0 because the start is already the destination.
Complexity
- Tree: time
O(n), spaceO(n). - Grid: time
O(m^2), spaceO(m^2).
Reference solution
from collections import deque
from typing import List
def tree_span_and_grid_escape(n: int, edges: List[List[int]], grid: List[List[int]]) -> List[int]:
adj = [[] for _ in range(n + 1)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
def farthest(start):
dist = [-1] * (n + 1)
dist[start] = 0
queue = deque([start])
far = start
while queue:
node = queue.popleft()
if dist[node] > dist[far]:
far = node
for nxt in adj[node]:
if dist[nxt] == -1:
dist[nxt] = dist[node] + 1
queue.append(nxt)
return far, dist[far]
if n == 1:
diameter = 0
else:
end_a, _ = farthest(1)
_, diameter = farthest(end_a)
if not grid or grid[0][0] == 1 or grid[-1][-1] == 1:
shortest = -1
else:
m = len(grid)
dist = [[-1] * m for _ in range(m)]
dist[0][0] = 0
queue = deque([(0, 0)])
moves = ((1, 0), (-1, 0), (0, 1), (0, -1))
while queue:
r, c = queue.popleft()
if r == m - 1 and c == m - 1:
break
for dr, dc in moves:
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < m and grid[nr][nc] == 0 and dist[nr][nc] == -1:
dist[nr][nc] = dist[r][c] + 1
queue.append((nr, nc))
shortest = dist[m - 1][m - 1]
return [diameter, shortest]