Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.Example 1:
Input:
0 0 0 0 1 0 0 0 0Output:
0 0 0 0 1 0 0 0 0
Example 2:
Input:
0 0 0 0 1 0 1 1 1Output:
0 0 0 0 1 0 1 2 1
Note:
Intuition
\nDo what the question says.
\nAlgorithm
\ndist[i][j]=INT_MAX
for all {i,j}
cells.0
, dist[i][j]=0
,1
cell,0
, calculate its distance from current cell as abs(k-i)+abs(l-j)
.Complexity Analysis
\nTime complexity: .\nIterating over the entire matrix for each 1
in the matrix.
Space complexity: .\nNo extra space required than the vector<vector<int> > dist
Intuition
\nA better brute force:\nLooking over the entire matrix appears wasteful and hence, we can use Breadth First Search(BFS) to limit the search to the nearest 0
found for each 1
. As soon as a 0
appears during the BFS, we know that the 0
is nearest, and hence, we move to the next 1
.
Think again:\nBut, in this approach, we will only be able to update the distance of one 1
using one BFS, which could in fact, result in slightly higher complexity than the Approach #1 brute force.\nBut hey,this could be optimised if we start the BFS from 0
s and thereby, updating the distances of all the 1
s in the path.
Algorithm
\nq
to maintain the queue of cells to be examined next.0
s to q
.0
cell is 0
and distance for each 1
is INT_MAX
, which is updated during the BFS.{i,j}
is smaller, we add {i,j}
to q
and update dist[i][j]
.Complexity analysis
\nSince, the new cells are added to the queue only if their current distance is greater than the calculated distance, cells are not likely to be added multiple times.
\nSpace complexity: . Additional for queue than in Approach #1
\nIntuition
\nThe distance of a cell from 0
can be calculated if we know the nearest distance for all the neighbours, in which case the distance is minimum distance of any neightbour + 1. And, instantly, the word come to mind DP!!
\nFor each 1
, the minimum path to 0
can be in any direction. So, we need to check all the 4 direction. In one iteration from top to bottom, we can check left and top directions, and we need another iteration from bottom to top to check for right and bottom direction.
Algorithm
\nComplexity analysis
\ndist vector<vector<int> >
Analysis written by @abhinavbansal0.
\n