This approach uses two additional arrays to track the rows and columns that need to be zeroed.
- Traverse the matrix and mark rows and columns that need to be zeroed.
- Then, update the matrix based on the values in these arrays.
Time Complexity: O(m * n), where m is the number of rows and n is the number of columns.
Space Complexity: O(m + n) for the additional arrays.
1#include <vector>
2using namespace std;
3
4void setZeroes(vector<vector<int>>& matrix) {
5 int m = matrix.size();
6 int n = matrix[0].size();
7 vector<bool> row(m, false);
8 vector<bool> col(n, false);
9
10 for(int i = 0; i < m; i++) {
11 for(int j = 0; j < n; j++) {
12 if(matrix[i][j] == 0) {
13 row[i] = true;
14 col[j] = true;
15 }
16 }
17 }
18
19 for(int i = 0; i < m; i++) {
20 for(int j = 0; j < n; j++) {
21 if(row[i] || col[j]) {
22 matrix[i][j] = 0;
23 }
24 }
25 }
26}
This approach uses the matrix itself to track zeroes.
- Use the first row and column as markers.
- Traverse the matrix and if an element is zero, mark its row and column.
- Traverse again and set matrix elements to zero based on marked rows and columns.
Time Complexity: O(m * n), where m is the number of rows and n is the number of columns.
Space Complexity: O(1) since the algorithm runs in constant space.
1#include <stdio.h>
2#include <stdbool.h>
3
4void setZeroes(int** matrix, int matrixSize, int* matrixColSize){
5 int isCol = 1;
6 int R = matrixSize;
7 int C = *matrixColSize;
8
9 for (int i = 0; i < R; i++) {
10 if (matrix[i][0] == 0) isCol = 0;
11 for (int j = 1; j < C; j++) {
12 if (matrix[i][j] == 0) {
13 matrix[i][0] = 0;
14 matrix[0][j] = 0;
15 }
16 }
17 }
18
19 for (int i = 1; i < R; i++) {
20 for (int j = 1; j < C; j++) {
21 if (matrix[i][0] == 0 || matrix[0][j] == 0) {
22 matrix[i][j] = 0;
23 }
24 }
25 }
26
27 if (matrix[0][0] == 0) {
28 for (int j = 0; j < C; j++) {
29 matrix[0][j] = 0;
30 }
31 }
32
33 if (isCol == 0) {
34 for (int i = 0; i < R; i++) {
35 matrix[i][0] = 0;
36 }
37 }
38}