|
1 | 1 | #include <stdio.h>
|
2 | 2 | #include <stdlib.h>
|
3 | 3 |
|
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) { |
6 | 6 | int *row_flag = (int *)calloc(m, sizeof(int));
|
7 | 7 | int *col_flag = (int *)calloc(n, sizeof(int));
|
8 | 8 |
|
@@ -31,6 +31,53 @@ void setZeroes(int **matrix, int m, int n) {
|
31 | 31 | }
|
32 | 32 | }
|
33 | 33 |
|
| 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 | + |
34 | 81 | int main() {
|
35 | 82 | int m, n, i, j;
|
36 | 83 | m = 5;
|
|
0 commit comments