Leetcode 73. Set Matrix Zeroes
Leetcode Problem 73: Set Matrix Zeroes
Given an m x n integer matrix matrix
, if an element is 0, set its entire row and column to 0’s. You must do it in place.
Input: matrix = [[1,1,1],
[1,0,1],
[1,1,1]]
Output: [[1,0,1],
[0,0,0],
[1,0,1]]
Input: matrix = [[0,1,2,0],
[3,4,5,2],
[1,3,1,5]]
Output: [[0,0,0,0],
[0,4,5,0],
[0,3,1,0]]
m == matrix.length
n == matrix[0].length
1 <= m, n <= 200
-2^31 <= matrix[i][j] <= 2^31 - 1
O(m*n)
space is probably a bad idea.O(m + n)
space.Q: Can we modify the input matrix directly? A: Yes, the problem statement requires us to modify the matrix in place.
Q: Can the matrix have any integer values including negative ones?
A: Yes, the elements of the matrix can range from -2^31
to 2^31 - 1
.
Q: Should we consider an empty matrix? A: No, given constraints ensure the matrix has dimensions at least 1x1.
#include <vector>
using namespace std;
void setZeroes(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
bool firstRowZero = false;
bool firstColZero = false;
// Check if the first row needs to be zero
for (int j = 0; j < n; ++j) {
if (matrix[0][j] == 0) {
firstRowZero = true;
break;
}
}
// Check if the first column needs to be zero
for (int i = 0; i < m; ++i) {
if (matrix[i][0] == 0) {
firstColZero = true;
break;
}
}
// Use the first row and column to mark zero rows and columns
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;
}
}
}
// Zero out cells based on marks
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;
}
}
}
// Handle the first row separately
if (firstRowZero) {
for (int j = 0; j < n; ++j) {
matrix[0][j] = 0;
}
}
// Handle the first column separately
if (firstColZero) {
for (int i = 0; i < m; ++i) {
matrix[i][0] = 0;
}
}
}
O(m * n)
because we traverse the entire matrix multiple times but with a constant number of operations on each cell.O(1)
as we are using only constant extra space for flags and modifying the matrix in place.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?