Skip to main content
mediumGrind 75

Distance to Nearest Zero

Also known as: 01 Matrix

Given a binary matrix of 0s and 1s Return a matrix where each cell contains the distance to the nearest 0 Distance = number of steps to adjacent cell (up/down/left/right) Example: [[0,0,0],[0,1,0],[1,1,1]] => [[0,0,0],[0,1,0],[1,2,1]]

I push every zero into the queue before the first step. One multi-source sweep gives each cell its nearest-zero distance.

Examples

You write

find_nearest_zero(matrix: List[List[int]])

  1. Example 1

    Input
    matrix = [[0,0,0],[0,1,0],[0,0,0]]
    returns
    [[0,0,0],[0,1,0],[0,0,0]]
  2. Example 2

    Input
    matrix = [[0,0,0],[0,1,0],[1,1,1]]
    returns
    [[0,0,0],[0,1,0],[1,2,1]]

The pattern behind it

Arrays & Hashing

I reach for it when

  • You catch yourself scanning the array again for every element.
  • The problem asks about duplicates, pairs, counts or groups.

Say this before you type. Say what the key is and what the value remembers, before you write the loop.

All 127 Arrays & Hashing problems

BFS & DFS

I reach for it when

  • You walk a grid, a graph or a tree and visit each cell once.
  • The word shortest appears and every step costs the same.

Say this before you type. Say why breadth or depth fits, and exactly when a cell counts as visited.

All 52 BFS & DFS problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Find Distance to Nearest Zeromedium