LeetCode OJ:Set Matrix Zeroes(设置矩阵0元素)
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
这题要注意的就是应该是就地执行,所以可以先采取一个数组将所有0元素的位置记下来,然后一次性的全部置成0即可:
1 class Solution { 2 public: 3 void setZeroes(vector<vector<int>>& matrix) { 4 int szHor = matrix.size(); 5 if(szHor == 0) return; 6 int szVer = matrix[0].size(); 7 if(szVer == 0) return; 8 vector<int> mark; 9 mark.clear(); 10 int i, j; 11 for(i = 0; i < szHor; ++i){ 12 for(j = 0; j < szVer; ++j){ 13 if(matrix[i][j] == 0){ 14 mark.push_back(i); 15 mark.push_back(j); 16 } 17 } 18 } 19 int row, col; 20 int sz = mark.size(); 21 for(int p = 0; p < sz; p+=2){ 22 for(int m = 0; m < szHor; m++){ 23 matrix[m][mark[p + 1]] = 0; 24 } 25 for(int n = 0; n < szVer; n++){ 26 matrix[mark[p]][n] = 0; 27 } 28 } 29 30 } 31 };