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.
1public class Solution {
2 public void SetZeroes(int[][] matrix) {
3 int m = matrix.Length;
4 int n = matrix[0].Length;
5 bool[] row = new bool[m];
6 bool[] col = new bool[n];
7
8 for (int i = 0; i < m; i++) {
9 for (int j = 0; j < n; j++) {
10 if (matrix[i][j] == 0) {
11 row[i] = true;
12 col[j] = true;
13 }
14 }
15 }
16
17 for (int i = 0; i < m; i++) {
18 for (int j = 0; j < n; j++) {
19 if (row[i] || col[j]) {
20 matrix[i][j] = 0;
21 }
22 }
23 }
24 }
25}
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.
1public class Solution {
2 public void setZeroes(int[][] matrix) {
3 int m = matrix.length;
4 int n = matrix[0].length;
5 boolean isCol = false;
6
7 for (int i = 0; i < m; i++) {
8 if (matrix[i][0] == 0) isCol = true;
9 for (int j = 1; j < n; j++) {
10 if (matrix[i][j] == 0) {
11 matrix[i][0] = 0;
12 matrix[0][j] = 0;
13 }
14 }
15 }
16
17 for (int i = 1; i < m; i++) {
18 for (int j = 1; j < n; j++) {
19 if (matrix[i][0] == 0 || matrix[0][j] == 0) {
20 matrix[i][j] = 0;
21 }
22 }
23 }
24
25 if (matrix[0][0] == 0) {
26 for (int j = 0; j < n; j++) {
27 matrix[0][j] = 0;
28 }
29 }
30
31 if (isCol) {
32 for (int i = 0; i < m; i++) {
33 matrix[i][0] = 0;
34 }
35 }
36 }
37}