Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit dc488d0

Browse files
author
Ram swaroop
committed
code done + unit tested
1 parent 6203d59 commit dc488d0

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package me.ramswaroop.arrays;
2+
3+
/**
4+
* Created by IntelliJ IDEA.
5+
*
6+
* @author: ramswaroop
7+
* @date: 9/11/15
8+
* @time: 3:28 PM
9+
* @see: http://www.geeksforgeeks.org/a-boolean-matrix-question/
10+
*/
11+
public class BooleanMatrix {
12+
13+
/**
14+
* Given a boolean matrix mat[M][N] of size M X N, modify it such that
15+
* if a matrix cell mat[i][j] is 1 (or true) then make all the cells of
16+
* ith row and jth column as 1.
17+
*
18+
* @param a
19+
*/
20+
public static void modifyBooleanMatrix(int[][] a) {
21+
int rowFlag = 0, colFlag = 0;
22+
23+
// if a[i][j] is 1 then we make a[0][j] 1 and a[i][0] 1
24+
for (int i = 0; i < a.length; i++) {
25+
for (int j = 0; j < a[0].length; j++) {
26+
if (i == 0 || j == 0) {
27+
if (a[i][0] == 1) {
28+
rowFlag = 1;
29+
}
30+
if (a[0][j] == 1) {
31+
colFlag = 1;
32+
}
33+
} else if (a[i][j] == 1) {
34+
a[0][j] = 1;
35+
a[i][0] = 1;
36+
}
37+
}
38+
}
39+
40+
// if a[0][j] is 1 or a[i][0] is 1 then a[i][j] is 1
41+
for (int i = 1; i < a.length; i++) {
42+
for (int j = 1; j < a[0].length; j++) {
43+
if (a[0][j] == 1 || a[i][0] == 1) {
44+
a[i][j] = 1;
45+
}
46+
}
47+
}
48+
49+
if (rowFlag == 1) {
50+
for (int j = 0; j < a[0].length; j++) {
51+
a[0][j] = 1;
52+
}
53+
}
54+
if (colFlag == 1) {
55+
for (int i = 0; i < a.length; i++) {
56+
a[i][0] = 1;
57+
}
58+
}
59+
}
60+
61+
private static void print2DMatrix(int[][] a) {
62+
for (int i = 0; i < a.length; i++) {
63+
for (int j = 0; j < a[0].length; j++) {
64+
System.out.print(a[i][j]);
65+
}
66+
System.out.println();
67+
}
68+
}
69+
70+
public static void main(String a[]) {
71+
int[][] ar = new int[][]{{1, 0, 0, 1}, {0, 0, 1, 0}, {0, 0, 0, 0}};
72+
print2DMatrix(ar);
73+
modifyBooleanMatrix(ar);
74+
print2DMatrix(ar);
75+
System.out.println("-------");
76+
ar = new int[][]{{1, 0}, {0, 0}};
77+
print2DMatrix(ar);
78+
modifyBooleanMatrix(ar);
79+
print2DMatrix(ar);
80+
}
81+
}

0 commit comments

Comments
 (0)