Set Matrix ZeroesTotal Accepted: 18139 Total Submissions: 58671 My Submissions
Given a m x n Matrix, if an element was 0, set its entire row and column to 0. Do it on place.
Click to show follow up.
Test instructions: Given a matrix, assume that a position of the matrix is 0. Set the entire element of that row to 0.
Idea: Use two bool arrays to record rows and columns where all elements should be set to 0
Complexity: Time O (m*n). Space O (m+n)
void Setzeroes (Vector<vector<int> > &matrix) {if (Matrix.empty ()) return; int rows = Matrix.size (), columns = matrix[0].size ();vector<bool> row (rows, False);vector<bool> column (columns, false); for (int i = 0; i < rows; ++i) {for (int j = 0; j < columns; ++j) {if (matrix[i][j] = = 0) {Row[i] = column[j] = true;continue;}}} for (int i = 0; i < rows; ++i) {if (!row[i]) continue;for (int j = 0; j < columns; ++j) {matrix[i][j] = 0;}} for (int j = 0; j < columns; ++j) {if (!column[j]) continue;for (int i = 0; i < rows; ++i) {matrix[i][j] = 0;}}
Leetcode Detail Implementation Set Matrix zeroes