class Solution {
public void setZeroes(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
// 创建一个新的矩阵,其中存放标志位,初始值都是0,经过重新赋值零之后,标志位改为1
int[][] flagMatrix = new int[rows][cols];
// 遍历初始矩阵,找到等于零的元素
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
// 找到0元素,并且判断其标志位是不是0
if(matrix[i][j] == 0 && flagMatrix[i][j] == 0){
// 对应列的所有元素都要置为0
for(int col = 0; col < cols; col++){
// 在i行当中
// 对于本身不为零的,置为零,且对应标志位置为1
if(matrix[i][col] != 0){
matrix[i][col] = 0;
flagMatrix[i][col] = 1;
}
}
// 对应列所有元素都要置为0
for(int row = 0; row < rows; row++){
// 在j行当中
// 对于本身不为零的,置为零,且对应标志位置为1
if(matrix[row][j] != 0){
matrix[row][j] = 0;
flagMatrix[row][j] = 1;
}
}
}
}
}
}
}
leetcode73:矩阵置零
最新推荐文章于 2024-06-10 23:49:13 发布