Given an M × N binary matrix, replace all occurrences of 0’s by 1’s, which are completely surrounded by 1’s from all sides (top, left, bottom, right, top-left, top-right, bottom-left, and bottom-right).

For example, consider the following matrix:

 [  1  1  1  1  0  0  1  1  0  1  ]
 [  1  0  0  1  1  0  1  1  1  1  ]
 [  1  0  0  1  1  1  1  1  1  1  ]
 [  1  1  1  1  0  0  1  1  0  1  ]
 [  0  0  1  1  0  0  0  1  0  1  ]
 [  1  0  0  1  1  0  1  1  0  0  ]
 [  1  1  0  1  1  1  1  1  1  1  ]
 [  1  1  0  1  1  0  0  1  0  1  ]
 [  1  1  1  0  1  0  1  0  0  1  ]
 [  1  1  1  0  1  1  1  1  1  1  ]

The solution should convert it into the following matrix:

 [  1  1  1  1  0  0  1  1  0  1  ]
 [  1  1  1  1  1  0  1  1  1  1  ]
 [  1  1  1  1  1  1  1  1  1  1  ]
 [  1  1  1  1  1  1  1  1  0  1  ]
 [  0  0  1  1  1  1  1  1  0  1  ]
 [  1  0  0  1  1  1  1  1  0  0  ]
 [  1  1  0  1  1  1  1  1  1  1  ]
 [  1  1  0  1  1  1  1  1  1  1  ]
 [  1  1  1  0  1  1  1  1  1  1  ]
 [  1  1  1  0  1  1  1  1  1  1  ]

Practice this problem

We can use the flood fill algorithm to solve this problem. The idea is to consider all zeros present on the matrix’s boundary one by one and start a Depth–first search (DFS) from them. The DFS procedure replaces all such connected zeros by value -1.

After processing all connected zeros present on the matrix boundary, traverse the matrix again, replace all remaining zeros with 1 and replace all -1 already present in the matrix back to zero.

 
The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
[1, 1, 1, 1, 0, 0, 1, 1, 0, 1]
[1, 1, 1, 1, 1, 0, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 0, 1]
[0, 0, 1, 1, 1, 1, 1, 1, 0, 1]
[1, 0, 0, 1, 1, 1, 1, 1, 0, 0]
[1, 1, 0, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 0, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 0, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 0, 1, 1, 1, 1, 1, 1]

The time complexity of the proposed solution is O(M × N) for an M × N matrix. The auxiliary space required by the program is O(M × N) for recursion (call stack).