class Solution {//passed without editing. worst case O(mn) space void zeroPropagate(vector<vector<int> > &matrix, int row, int col){ for(int ii = 0; ii < matrix.size(); ++ii){ matrix[ii][col] = 0; } for(int ii = 0; ii < matrix[0].size(); ++ii){ matrix[row][ii] = 0; } } public: void setZeroes(vector<vector<int> > &matrix) { // Start typing your C/C++ solution below // DO NOT write int main() function if (matrix.empty() || matrix[0].empty()) return; vector<pair<int,int> > record; for(int ii = 0; ii < matrix.size(); ++ii){ for(int jj = 0; jj < matrix[0].size(); ++jj){ if (matrix[ii][jj] == 0) record.push_back(pair<int,int>(ii,jj)); } } for(int ii = 0; ii < record.size(); ++ii){ zeroPropagate(matrix, record[ii].first, record[ii].second); } } };
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.
Could you devise a constant space solution?
class Solution {//follow up: constant extra space public: void setZeroes(vector<vector<int> > &matrix) { //mark zeroes at the edge of matrix[][] if (matrix.empty() || matrix[0].empty()) return; bool init_col_zero = false; bool init_row_zero = false; for(int ii = 0; ii < matrix.size(); ++ii){ if (matrix[ii][0] == 0){ init_col_zero = true; break; } } for(int jj = 0; jj < matrix[0].size(); ++jj){ if (matrix[0][jj] == 0){ init_row_zero = true; break; } } for(int ii = 1; ii < matrix.size();++ii){ for(int jj = 1; jj < matrix[0].size(); ++jj){ if (matrix[ii][jj] == 0){ matrix[0][jj] = 0; matrix[ii][0] = 0; } }//for jj }//for ii for(int ii = 1; ii < matrix.size(); ++ii){//paint rows if (matrix[ii][0] == 0) matrix[ii].assign(matrix[0].size(), 0); } for(int jj = 1; jj < matrix[0].size(); ++jj){//paint columns if (matrix[0][jj] == 0){ for(int ii = 1; ii < matrix.size(); ++ii){ matrix[ii][jj] = 0; } } } if (init_row_zero) matrix[0].assign(matrix[0].size(), 0); if (init_col_zero){ for(int ii = 0; ii < matrix.size(); ++ii){ matrix[ii][0] = 0; } } } };
No comments:
Post a Comment