MCPcopy Create free account
hub / github.com/careercup/ctci / setZeros2

Method setZeros2

java/Chapter 1/Question1_7/Question.java:18–71  ·  view source on GitHub ↗
(int[][] matrix)

Source from the content-addressed store, hash-verified

16 }
17
18 public static void setZeros2(int[][] matrix) {
19 boolean rowHasZero = false;
20 boolean colHasZero = false;
21
22 // Check if first row has a zero
23 for (int j = 0; j < matrix[0].length; j++) {
24 if (matrix[0][j] == 0) {
25 rowHasZero = true;
26 break;
27 }
28 }
29
30 // Check if first column has a zero
31 for (int i = 0; i < matrix.length; i++) {
32 if (matrix[i][0] == 0) {
33 colHasZero = true;
34 break;
35 }
36 }
37
38 // Check for zeros in the rest of the array
39 for (int i = 1; i < matrix.length; i++) {
40 for (int j = 1; j < matrix[0].length;j++) {
41 if (matrix[i][j] == 0) {
42 matrix[i][0] = 0;
43 matrix[0][j] = 0;
44 }
45 }
46 }
47
48 // Nullify rows based on values in first column
49 for (int i = 1; i < matrix.length; i++) {
50 if (matrix[i][0] == 0) {
51 nullifyRow(matrix, i);
52 }
53 }
54
55 // Nullify columns based on values in first row
56 for (int j = 1; j < matrix[0].length; j++) {
57 if (matrix[0][j] == 0) {
58 nullifyColumn(matrix, j);
59 }
60 }
61
62 // Nullify first row
63 if (rowHasZero) {
64 nullifyRow(matrix, 0);
65 }
66
67 // Nullify first column
68 if (colHasZero) {
69 nullifyColumn(matrix, 0);
70 }
71 }
72
73 public static void setZeros(int[][] matrix) {
74 boolean[] row = new boolean[matrix.length];

Callers 1

mainMethod · 0.95

Calls 2

nullifyRowMethod · 0.95
nullifyColumnMethod · 0.95

Tested by

no test coverage detected