Mark Matrix Zeros

By   Tewodros   Date Posted: Feb. 27, 2024  Hits: 264   Category:  Algorithm   Total Comment: 0             A+ A-


side

Mark matrix corresponding  row and column 0 if you find 0 at the given index (i,j)

Example

Input

[1  1   1]

[1  0   1]

[1  1   1]

 

Output

[1  0  1]

[0  0  0]

[1  0   1]

 

 

 

     public class Solution {

   public void SetZeroes(int[][] matrix) {

       int m = matrix.Length;

       int n = matrix[0].Length;

       

       bool firstRowZero = false;

       bool firstColZero = false;

       

       // Check if the first row contains zero

       for (int j = 0; j < n; j++) {

           if (matrix[0][j] == 0) {

               firstRowZero = true;

               break;

           }

       }

       

       // Check if the first column contains zero

       for (int i = 0; i < m; i++) {

           if (matrix[i][0] == 0) {

               firstColZero = true;

               break;

           }

       }

       

       // Use the first row and first column to mark rows and columns containing zeros

       for (int i = 1; i < m; i++) {

           for (int j = 1; j < n; j++) {

               if (matrix[i][j] == 0) {

                   matrix[i][0] = 0;

                   matrix[0][j] = 0;

               }

           }

       }

       

       // Set rows and columns to zero based on marks in the first row and first column

       for (int i = 1; i < m; i++) {

           for (int j = 1; j < n; j++) {

               if (matrix[i][0] == 0 || matrix[0][j] == 0) {

                   matrix[i][j] = 0;

               }

           }

       }

       

       // Set the first row to zero if needed

       if (firstRowZero) {

           for (int j = 0; j < n; j++) {

               matrix[0][j] = 0;

           }

       }

       

       // Set the first column to zero if needed

       if (firstColZero) {

           for (int i = 0; i < m; i++) {

               matrix[i][0] = 0;

           }

       }

   }

}

 

 


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* admhkq

Back to Top