Leetcode 73. Set Matrix Zeroes | | Leetcode 73. Set Matrix Zeroes 文章作者:Tyan博客:noahsnail.com | CSDN | 简书 1. Description 2. Solution Version 1 123456789101112131415161718192021222324252627282930class Solution {public: void setZeroes(vector<vector<int>>& matrix) { int rows = matrix.size(); if(rows == 0) { return; } int columns = matrix[0].size(); vector<int> row; vector<int> column; for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) { if(!matrix[i][j]) { row.push_back(i); column.push_back(j); } } } for(int i = 0; i < row.size(); i++) { for(int j = 0; j < columns; j++) { matrix[row[i]][j] = 0; } } for(int j = 0; j < column.size(); j++) { for(int i = 0; i < rows; i++) { matrix[i][column[j]] = 0; } } }}; Version 2 12345678910111213141516171819202122232425262728293031323334353637383940414243class Solution {public: void setZeroes(vector<vector<int>>& matrix) { int rows = matrix.size(); if(rows == 0) { return; } int columns = matrix[0].size(); bool row = false; bool column = false; for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) { if(!matrix[i][j]) { if(!i) { row = true; } if(!j) { column = true; } matrix[0][j] = 0; matrix[i][0] = 0; } } } for(int i = 1; i < rows; i++) { for(int j = 1; j < columns; j++) { if(!matrix[0][j] || !matrix[i][0]) { matrix[i][j] = 0; } } } if(row) { for(int j = 0; j < columns; j++) { matrix[0][j] = 0; } } if(column) { for(int i = 0; i < rows; i++) { matrix[i][0] = 0; } } }}; Reference https://leetcode.com/problems/set-matrix-zeroes/description/ 如果有收获,可以请我喝杯咖啡! 赏 微信打赏 支付宝打赏