-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSet Matrix Zeroes
52 lines (46 loc) · 1.49 KB
/
Set Matrix Zeroes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
Question - Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's, and return the matrix.
You must do it in place.
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
package com.company;
import java.util.Scanner;
public class MatrixZeros {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter the no of rows and columns");
int r = sc.nextInt();
int c = sc.nextInt();
int i,j,k;
int[][] arr = new int[r][c];
System.out.println("enter the no of row and col elements");
for (i=0;i<r;i++){
for ( j=0;j<c;j++) {
arr[i][j] = sc.nextInt();
}
}
int[][] temp = new int[r][c];
for (i=0;i<r;i++) {
for (j = 0; j < c; j++) {
temp[i][j] = arr[i][j];
}
}
for (i=0;i<r;i++) {
for (j = 0; j < c; j++) {
if (arr[i][j] == 0) {
for (k = 0; k < r; k++)
temp[i][k] = 0;
for (k = 0; k < c; k++)
temp[k][j] = 0;
}
}
}
System.out.println("Your Zero Matrix output is:");
for (i=0;i<r;i++){
for (j=0;j<c;j++){
arr[i][j] = temp[i][j];
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}