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