Graph Theory37 sections · 1633 units
Open in Course

LeetCode 542 01 Matrix - Core Idea

Reverse the perspective

You could run BFS from each 11 cell to find the nearest 00.

But if there are nn cells with 11, you'd run BFS nn times. That's O(n×rows×cols)O(n \times rows \times cols), which can time out.

Instead, reverse the problem. Push all 00 cells into the queue at distance 00. Then run BFS once. As you spread outward, you discover 11 cells at distance 11, then 11 cells at distance 22, and so on.

Why does this work? Because BFS explores in order of increasing distance. The first time you reach a 11 cell from any 00 cell, that's the shortest distance. You never need to revisit it.