Skip to content

Commit 4b96bb9

Browse files
committed
"Set Matrix Zeroes": O(1) space
1 parent 9859a7d commit 4b96bb9

File tree

1 file changed

+49
-2
lines changed

1 file changed

+49
-2
lines changed

src/73.c

+49-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
#include <stdio.h>
22
#include <stdlib.h>
33

4-
/* space: O(m+n) */
5-
void setZeroes(int **matrix, int m, int n) {
4+
/* space: O(m+n) time: O(m*n) */
5+
void setZeroes_1(int **matrix, int m, int n) {
66
int *row_flag = (int *)calloc(m, sizeof(int));
77
int *col_flag = (int *)calloc(n, sizeof(int));
88

@@ -31,6 +31,53 @@ void setZeroes(int **matrix, int m, int n) {
3131
}
3232
}
3333

34+
/* space: O(1) time: O(m*n)
35+
* use first column to set row flag
36+
* and first row to set column flag */
37+
void setZeroes(int **matrix, int m, int n) {
38+
int first_col_zero, first_row_zero;
39+
first_col_zero = first_row_zero = 0;
40+
int i, j;
41+
/* scan first column */
42+
for (i = 0; i < m; i++) {
43+
if (matrix[i][0] == 0) {
44+
first_col_zero = 1;
45+
break;
46+
}
47+
}
48+
/* scan first row */
49+
for (j = 0; j < n; j++) {
50+
if (matrix[0][j] == 0) {
51+
first_row_zero = 1;
52+
break;
53+
}
54+
}
55+
/* scan the matrix */
56+
for (i = 0; i < m; i++) {
57+
for (j = 0; j < n; j++) {
58+
if (matrix[i][j] == 0) {
59+
matrix[i][0] = 0;
60+
matrix[0][j] = 0;
61+
}
62+
}
63+
}
64+
/* set zeros except first column and first row */
65+
for (i = 1; i < m; i++) {
66+
for (j = 1; j < n; j++) {
67+
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
68+
matrix[i][j] = 0;
69+
}
70+
}
71+
}
72+
/* set first column and first row to zero */
73+
if (first_col_zero) {
74+
for (i = 0; i < m; i++) matrix[i][0] = 0;
75+
}
76+
if (first_row_zero) {
77+
for (j = 0; j < n; j++) matrix[0][j] = 0;
78+
}
79+
}
80+
3481
int main() {
3582
int m, n, i, j;
3683
m = 5;

0 commit comments

Comments
 (0)