void setZeroes(vector<vector<int>>& matrix) { int m = matrix.size(), n = matrix[0].size(); bool firstRowZero = false, firstColZero = false; for (int i = 0; i < m; i++) { if (matrix[i][0] == 0) firstColZero = true; } for (int j = 0; j < n; j++) { if (matrix[0][j] == 0) firstRowZero = true; } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { if (matrix[i][j] == 0) { matrix[i][0] = 0; matrix[0][j] = 0; } } } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { if (matrix[i][0] == 0 || matrix[0][j] == 0) { matrix[i][j] = 0; } } } if (firstColZero) { for (int i = 0; i < m; i++) matrix[i][0] = 0; } if (firstRowZero) { for (int j = 0; j < n; j++) matrix[0][j] = 0; } } // Initial matrix: // [[1,1,1],[1,0,1],[1,1,1]] // After calling setZeroes(matrix), what is matrix?
The code first checks if the first row or first column contains zero and stores that info. Then it marks the first cell of rows and columns that contain zero. Finally, it updates the matrix cells to zero based on these marks. The first row and column are updated last if needed.
Using the first row and column as markers allows the algorithm to remember which rows and columns to zero without extra arrays, achieving O(1) additional space.
void setZeroes(vector<vector<int>>& matrix) { int m = matrix.size(), n = matrix[0].size(); bool firstRowZero = false, firstColZero = false; for (int i = 0; i < m; i++) { if (matrix[i][0] == 0) firstColZero = true; } for (int j = 0; j < n; j++) { if (matrix[0][j] == 0) firstRowZero = true; } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { if (matrix[i][j] == 0) { matrix[i][0] = 0; matrix[0][j] = 0; } } } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { if (matrix[i][0] == 0 || matrix[0][j] == 0) { matrix[i][j] = 0; } } } if (firstColZero) { for (int i = 0; i < m; i++) matrix[i][0] = 0; } if (firstRowZero) { for (int j = 0; j < n; j++) matrix[0][j] = 0; } } // Initial matrix: // [[0,1,2,0],[3,4,5,2],[1,3,1,5]] // After calling setZeroes(matrix), what is matrix?
The zeros at positions (0,0) and (0,3) cause the entire first row and first column and the last column to be zeroed. The rest of the matrix updates accordingly.
This approach uses two extra arrays to track rows and columns to zero, increasing space complexity to O(m+n) instead of O(1).
The optimal in-place algorithm requires three passes: first to mark zeroes in the first row and column, second to update the matrix based on marks, and third to update the first row and column if needed.
