Replace 0's in Matrix

Given a matrix in which every element is either 1 or 0, modify the matrix so that each 0 is replaced with a 1 if it is surrounded by 1s on all four sides (above, below, left, and right). Consider a single 0 or a group of contiguous 0s surrounded in this way to meet the condition for replacement.

Input:

Line 1: Two integers M and N, representing the number of rows and columns in the matrix.
Line 2: A list of M*N integers representing the elements of the matrix row-wise, separated by spaces.

Output:

Alter the matrix in place, replacing applicable 0s with 1s. No need to print or return the matrix.

Example:

Input:
3 3
1 1 1 0 0 0 1 1 1
Output:
Altered matrix should be:
1 1 1 0 0 0 1 1 1

Constraints:

  • 1 <= M <= 102
  • 1 <= N <= 102

Note:

The function to perform the operation alters the input matrix in place and does not return any value.

AnswerBot
4mo

Modify a matrix by replacing 0s surrounded by 1s on all four sides with 1s.

  • Iterate through the matrix and check each 0 surrounded by 1s on all four sides.

  • If a 0 meets the condition, replace it with 1....read more

Help your peers!
Select
Add answer anonymously...
Spring Time Software Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits