We are required to replace each 1 in the given array with the distance to the nearest 0.
This problem tricks one into using DFS (at least it did to me), because one would think to find a 0 its best to do a DFS in all directions after arriving at a 1. Turns out that does not work, and if you try to make it work there are multiple repeated computations.
Instead, try a BFS. And instead of finding a 1 from 0, do the opposite.
Note: While adding neighbours of the current element to the queue, make sure to use direction vectors, else the code is going to look wild xD
Code:
Java
Big O Analysis
Runtime
The runtime complexity here is O(N) as since we would be iterating the array once.