-
Notifications
You must be signed in to change notification settings - Fork 129
/
Zero_matrix.java
82 lines (80 loc) · 3.21 KB
/
Zero_matrix.java
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import java.util.*;
class Zero_matrix {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of rows and cols: ");
int m = sc.nextInt();
int n = sc.nextInt();
int arr[][] = new int[m][n];
int zarr[][]=new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.println("Enter val: ");
zarr[i][j]=arr[i][j] = sc.nextInt();
}
}
System.out.println("Given Matrix: ");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (arr[i][j] == 0) {
// System.out.println(i+" "+j);
if (i == 0) {
if (j == 0){
zarr[i][j + 1] = zarr[i + 1][j] = 0;
zarr[i][j]=arr[i][j+1]+arr[i+1][j];
}
else if (j == (n-1)){
zarr[i][j - 1] = zarr[i + 1][j] = 0;
zarr[i][j]=arr[i][j-1]+arr[i+1][j];
}
else{
zarr[i][j + 1] = zarr[i + 1][j] = zarr[i][j - 1] = 0;
zarr[i][j]=arr[i][j+1]+arr[i][j-1]+arr[i+1][j];
}
}
else if (i == (m-1)) {
if (j == 0){
zarr[i][j + 1] = zarr[i - 1][j] = 0;
zarr[i][j]=arr[i][j+1]+arr[i-1][j];
}
else if (j == (n-1)){
zarr[i][j - 1] = zarr[i - 1][j] = 0;
zarr[i][j]=arr[i][j-1]+arr[i-1][j];
}
else{
zarr[i][j + 1] = zarr[i][j - 1] = zarr[i - 1][j] = 0;
zarr[i][j]=arr[i][j+1]+arr[i][j-1]+arr[i-1][j];
}
}
else {
if (j == 0){
zarr[i][j + 1] = zarr[i + 1][j]=zarr[i-1][j] = 0;
zarr[i][j]=arr[i][j+1]+arr[i+1][j]+arr[i-1][j];
}
else if (j == (n-1)){
zarr[i][j - 1] = zarr[i + 1][j]=zarr[i-1][j] = 0;
zarr[i][j]=arr[i][j-1]+arr[i+1][j]+arr[i-1][j];
}
else{
zarr[i][j + 1] = zarr[i + 1][j] = zarr[i][j - 1]=zarr[i-1][j]= 0;
zarr[i][j]=arr[i][j+1]+arr[i][j-1]+arr[i+1][j]+arr[i-1][j];
}
}
}
}
}
System.out.println("Zero Matrix: ");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(zarr[i][j] + " ");
}
System.out.println();
}
}
}