Set matrix zeroes
(Link: https://oj.leetcode.com/problems/set-matrix-zeroes)
GivenMXNMatrix, if an element is 0, set its entire row and column to 0. Do it in place.
Click to show follow up.
Follow up:
Did you use extra space? A straight forward solution using O (MN) Space is probably a bad idea. A simple improvement Uses O (M+N) Space, but still not the best solution. cocould you devise a constant space solution?
Idea: Find the first zero element and write down its rows and columns. Then, the other 0 elements are projected into the recorded rows and columns (marked) respectively ). After the traversal, the column where all rows are marked is set to 0; for all columns, the row where all columns are marked is set to 0. (the last row and column marked with 0. time: O (n2), Space: O (1)
class Solution {public:void setZeroes(vector<vector<int> > &matrix) {if(!matrix.size() || !matrix[0].size()) return;const int INF = 1001;int row = matrix.size(), col = matrix[0].size();int u = -1, v = -1;for(int r = 0; r < row; ++r) for(int c = 0; c < col; ++c) {if(matrix[r][c] == 0) {if(u == -1) { u = r, v = c; continue; }matrix[u][c] = INF;matrix[r][v] = INF;}}if(u == -1) return;if(matrix[u][v] == INF) matrix[u][v] = 0;for(int c = 0; c < col; ++c) {if(matrix[u][c] == INF) {for(int i = 0; i < row; ++i) matrix[i][c] = 0;} else matrix[u][c] = 0;}for(int r = 0; r < row; ++r) {if(matrix[r][v] == INF) {for(int j = 0; j < col; ++j) matrix[r][j] = 0;} else matrix[r][v] = 0;}}};
55. Set matrix zeroes