Given an M × N binary matrix, replace all occurrences of 0’s by 1’s, which are not 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  ]
 [  1  1  1  1  0  0  0  1  0  1  ]
 [  1  1  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  1  1  1  1  1  1  ]
 [  1  0  0  1  1  1  1  1  1  1  ]
 [  1  0  0  1  1  1  1  1  1  1  ]
 [  1  1  1  1  0  0  1  1  1  1  ]
 [  1  1  1  1  0  0  0  1  1  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  0  0  1  0  1  ]
 [  1  1  1  1  1  0  1  0  0  1  ]
 [  1  1  1  1  1  1  1  1  1  1  ]

Practice this problem

We can use Depth–first search (DFS) to solve this problem. The idea is to consider all zeros present on the matrix boundary one by one and start a depth–first search from them to replace all connected 0’s. Note that we don’t need a visited array here as we are replacing every processed node’s value, and it won’t be considered again next time as it will have value 1.

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

C++


Download  Run Code

Output:

1  1  1  1  1  1  1  1  1  1
1  0  0  1  1  1  1  1  1  1
1  0  0  1  1  1  1  1  1  1
1  1  1  1  0  0  1  1  1  1
1  1  1  1  0  0  0  1  1  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  0  0  1  0  1
1  1  1  1  1  0  1  0  0  1
1  1  1  1  1  1  1  1  1  1

Java


Download  Run Code

Output:

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 0, 0, 1, 1, 1, 1, 1, 1, 1]
[1, 0, 0, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 0, 0, 1, 1, 1, 1]
[1, 1, 1, 1, 0, 0, 0, 1, 1, 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, 0, 0, 1, 0, 1]
[1, 1, 1, 1, 1, 0, 1, 0, 0, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

Python


Download  Run Code

Output:

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 0, 0, 1, 1, 1, 1, 1, 1, 1]
[1, 0, 0, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 0, 0, 1, 1, 1, 1]
[1, 1, 1, 1, 0, 0, 0, 1, 1, 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, 0, 0, 1, 0, 1]
[1, 1, 1, 1, 1, 0, 1, 0, 0, 1]
[1, 1, 1, 1, 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).