Zero Row and Zero Column

Given a matrix A of size N x M. Elements of the matrix are either 0 or 1. If A[i][j] = 0, set all the elements in the ith row and jth column to 0. Print the resultant matrix.

Input Format

First line of input contains N, M – the size of the matrix A. Its followed by N lines each containing M integers – elements of the matrix.

Constraints

1 <= N, M <= 100
A[i][j] ∈ {0,1}

Output Format

Print the resultant matrix.

InputcopyOutputcopy
4 5
0 1 1 0 1
1 1 1 1 1
1 1 0 1 1
1 1 1 1 1
0 0 0 0 0
0 1 0 0 1
0 0 0 0 0
0 1 0 0 1
import java.util.Scanner;
public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int rows = sc.nextInt();
        int cols = sc.nextInt();

        int arr[][] = new int[rows][cols];

        for(int i=0; i<rows; i++){
            for(int j=0; j<cols; j++){
                arr[i][j] = sc.nextInt();
            }
        }

        boolean row[] = new boolean[rows];
        boolean col[] = new boolean[cols];

        for(int i=0; i<rows; i++){
            for(int j=0; j<cols; j++){
                if(arr[i][j]==0){
                    row[i]=true;
                    col[j]=true;
                }

            }
        }

        for(int i=0; i<rows; i++){
            for(int j=0; j<cols; j++){
                if(row[i] || col[j]){
                    arr[i][j]=0;
                }

            }
        }

        for(int i=0; i<rows; i++){
            for(int j=0; j<cols; j++){
                System.out.print(arr[i][j]+" ");
            }
            System.out.println();
        }
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top