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.

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, and to talk with her for one hour. After that, talking comes with the $79 pack. Anyone can open the editor and run their code.

1Find Distance to Nearest Zeromedium
Based onLeetCode

Get a note when something new lands

New company guides, new problems and big changes to Coco. Rare, and you can leave any time. By joining you agree to get these emails.