|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | + |
| 4 | +/* space: O(m+n) */ |
| 5 | +void setZeroes(int **matrix, int m, int n) { |
| 6 | + int *row_flag = (int *)calloc(m, sizeof(int)); |
| 7 | + int *col_flag = (int *)calloc(n, sizeof(int)); |
| 8 | + |
| 9 | + int i, j, ii, jj; |
| 10 | + for (i = 0; i < m; i++) { |
| 11 | + for (j = 0; j < n; j++) { |
| 12 | + if (matrix[i][j] == 0) { |
| 13 | + row_flag[i] = 1; |
| 14 | + col_flag[j] = 1; |
| 15 | + } |
| 16 | + } |
| 17 | + } |
| 18 | + for (j = 0; j < n; j++) { |
| 19 | + if (col_flag[j]) { |
| 20 | + for (ii = 0; ii < m; ii++) { |
| 21 | + matrix[ii][j] = 0; |
| 22 | + } |
| 23 | + } |
| 24 | + } |
| 25 | + for (i = 0; i < m; i++) { |
| 26 | + if (row_flag[i]) { |
| 27 | + for (jj = 0; jj < n; jj++) { |
| 28 | + matrix[i][jj] = 0; |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +int main() { |
| 35 | + int m, n, i, j; |
| 36 | + m = 5; |
| 37 | + n = 4; |
| 38 | + |
| 39 | + int **matrix = (int **)calloc(m, sizeof(int *)); |
| 40 | + for (i = 0; i < m; i++) |
| 41 | + matrix[i] = (int *)calloc(n, sizeof(int)); |
| 42 | + |
| 43 | + matrix[0][0] = 0; matrix[0][1] = 0; matrix[0][2] = 0; matrix[0][3] = 5; |
| 44 | + matrix[1][0] = 4; matrix[1][1] = 3; matrix[1][2] = 1; matrix[1][3] = 4; |
| 45 | + matrix[2][0] = 0; matrix[2][1] = 1; matrix[2][2] = 1; matrix[2][3] = 4; |
| 46 | + matrix[3][0] = 1; matrix[3][1] = 2; matrix[3][2] = 1; matrix[3][3] = 3; |
| 47 | + matrix[4][0] = 0; matrix[4][1] = 0; matrix[4][2] = 1; matrix[4][3] = 1; |
| 48 | + |
| 49 | + setZeroes(matrix, m, n); |
| 50 | + |
| 51 | + for (i = 0; i < m; i++) { |
| 52 | + for (j = 0; j < n; j++) { |
| 53 | + printf("%d ", matrix[i][j]); |
| 54 | + } |
| 55 | + printf("\n"); |
| 56 | + } |
| 57 | + |
| 58 | + return 0; |
| 59 | +} |
0 commit comments