Column Grid from a Tree: Reach a Value by Walking Non-Zero Cells
Trees & GraphsAuto-graded · 23 test casesLast updated
Project a heap-indexed binary tree onto a depth-by-column grid, then use BFS over non-zero cells to decide whether a cell holding the target is reachable from a given start.
Tree on a Grid
A binary tree is given as a level-order list using heap indexing. The node at index i has its left child at index 2i + 1 and its right child at index 2i + 2. A None entry means that position has no node. Children of a missing node are never part of the tree, even if the list has non-None values at those indices.
Step 1: assign coordinates
Each node gets a depth and a column:
- The root has depth
0and column0. - A left child has its parent's depth plus 1 and its parent's column minus 1.
- A right child has its parent's depth plus 1 and its parent's column plus 1.
Step 2: build the grid
Build a 2D grid with:
max_depth + 1rows, wheremax_depthis the largest depth of any node.- One column for each column index from the smallest to the largest used by any node. Shift the indices so the smallest column becomes grid column
0.
Every cell starts as 0. Then write each node's value into the cell at (depth, column - min_column).
Two different nodes can land in the same cell. Process nodes in increasing index order (level order), so the node that comes later in the list overwrites the earlier one.
Step 3: walk the grid
You are given a starting cell (start_row, start_col), expressed in the shifted grid coordinates, and an integer target. From a cell you may move up, down, left, or right, but only into cells whose value is non-zero.
Return True if some cell holding target can be reached from the start, including the start cell itself (zero moves). Return False otherwise.
Special cases
- If the list is empty or its first element is
None, returnFalse. - If the start cell is outside the grid, return
False. - If the start cell holds
0, returnFalse. - The target is never reachable if it is
0or does not appear in the grid.
Function
Implement grid_reach(tree, start_row, start_col, target) returning a boolean.
Constraints
- The tree has at most 10^4 nodes.
- Every node value is a non-zero integer.
start_row,start_col, andtargetare integers. The start may lie outside the grid.- Grid dimensions come entirely from the tree's shape as described above.
Examples
Example 1
Input: grid_reach([1, 2, 3, 4, None, 5, 6], 0, 1, 5)
Output: False
Example 2
Input: grid_reach([1], 0, 0, 1)
Output: True
Example 3
Input: grid_reach([1, 2, 3], 0, 0, 9)
Output: False
Hints
Hint 1
First turn the list into (depth, column, value) triples. A BFS from index 0 that only enqueues non-None children handles missing subtrees automatically.
Hint 2
Compute the minimum and maximum column and the maximum depth, allocate the grid, and fill it in the order the nodes were discovered so later nodes overwrite earlier ones.
Hint 3
Check the start cell for bounds and for zero before searching, then run a standard 4-direction BFS over non-zero cells, testing each dequeued cell against the target.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task has three stages, and each one is solved directly.
- Coordinates. Run a BFS over the heap-indexed list starting at index 0, carrying
(index, depth, column). A left child getscolumn - 1and a right child getscolumn + 1. Only non-Nonechildren are enqueued, so anything below a missing node is never visited. Record each node as(depth, column, value)in discovery order, which is increasing index order. - Grid. Compute the minimum and maximum column and the maximum depth. Allocate a
(max_depth + 1) x (max_col - min_col + 1)grid of zeros and write each recorded value at(depth, column - min_col). Writing in discovery order makes later nodes overwrite earlier ones when two nodes share a cell, as the statement requires. - Reachability. If the start is out of bounds or holds
0, returnFalse. Otherwise run a 4-direction BFS that only enters non-zero cells and tracks visited cells. ReturnTrueas soon as a dequeued cell equalstarget. If the queue empties, returnFalse.
Why it is correct
- Depth and column follow the same parent-to-child rule the statement gives, and the BFS applies that rule to every node that actually exists, so each node gets its true coordinates.
- Columns used by a tree are contiguous, because the path from the root to an extreme column passes through every column in between. The grid width is therefore exactly the number of distinct columns.
- BFS from a vertex visits precisely its connected component. Here the vertices are the non-zero cells and the edges join 4-adjacent ones. The target is reachable exactly when a cell equal to it lies in the start's component. Checking at dequeue time also covers the zero-move case.
- Because only non-zero cells are ever entered, a target of
0can never be found.
Side observation. A node's depth and column always have the same parity, since each step changes both by exactly 1. Two 4-adjacent cells differ in the parity of row + col, so no two non-zero cells are ever adjacent. The BFS component is therefore always just the start cell, and the answer reduces to "the start is in bounds and holds target". The general BFS above is still the faithful implementation and gives identical results.
Complexity
Let V be the number of nodes, D the depth, and W the number of columns.
- Time: O(V + D * W) to place nodes, allocate the grid, and run the BFS.
- Space: O(D * W) for the grid and visited set, plus O(V) for the node records.
Reference solution
from collections import deque
from typing import List, Optional
def grid_reach(tree: List[Optional[int]], start_row: int, start_col: int, target: int) -> bool:
if not tree or tree[0] is None:
return False
# Stage 1: discover nodes in level order with their coordinates.
placed = [(0, 0, tree[0])]
queue = deque([(0, 0, 0)]) # (index, depth, column)
while queue:
index, depth, column = queue.popleft()
for child_index, child_column in ((2 * index + 1, column - 1),
(2 * index + 2, column + 1)):
if child_index < len(tree) and tree[child_index] is not None:
placed.append((depth + 1, child_column, tree[child_index]))
queue.append((child_index, depth + 1, child_column))
# Stage 2: build the grid; later nodes overwrite earlier ones.
min_col = min(c for _, c, _ in placed)
max_col = max(c for _, c, _ in placed)
max_depth = max(d for d, _, _ in placed)
grid = [[0] * (max_col - min_col + 1) for _ in range(max_depth + 1)]
for depth, column, value in placed:
grid[depth][column - min_col] = value
# Stage 3: validate the start, then BFS across non-zero cells.
rows, cols = len(grid), len(grid[0])
if not (0 <= start_row < rows and 0 <= start_col < cols):
return False
if grid[start_row][start_col] == 0:
return False
visited = {(start_row, start_col)}
queue = deque([(start_row, start_col)])
while queue:
r, c = queue.popleft()
if grid[r][c] == target:
return True
for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
if (0 <= nr < rows and 0 <= nc < cols
and (nr, nc) not in visited and grid[nr][nc] != 0):
visited.add((nr, nc))
queue.append((nr, nc))
return False