矩阵置0
问题描述:
给定一个
m x n
的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0。示例 1:
输入:matrix = [[1,1,1],[1,0,1],[1,1,1]] 输出:[[1,0,1],[0,0,0],[1,0,1]]示例 2:
输入:matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]] 输出:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]思路分析:
先第一次扫描数组,找到为0的元素,然后将其所在的行和列进行标记(boolean true为0);再次扫描数组,将标记为true的数组元素置为0。
//提交版
class Solution {
public int[][] setZeroes(int[][] matrix) {
//矩阵的行数
int m = matrix.length;
//矩阵的列数
int n = matrix[0].length;
boolean[] row = new boolean[m];
boolean[] col = new boolean[n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0) {
row[i] = true;
col[j] = true;
}
}
}
for (int k = 0; k < m; k++) {
for (int l = 0; l < n; l++) {
if (row[k] || col[l]) {
matrix[k][l] = 0;
}
}
}
return matrix;
}
}
//带有输入输出版本
import java.util.Arrays;
public class hot15_setZeroes {
public int[][] setZeroes(int[][] matrix) {
//矩阵的行数
int m = matrix.length;
//矩阵的列数
int n = matrix[0].length;
boolean[] row = new boolean[m];
boolean[] col = new boolean[n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0) {
row[i] = true;
col[j] = true;
}
}
}
for (int k = 0; k < m; k++) {
for (int l = 0; l < n; l++) {
if (row[k] || col[l]) {
matrix[k][l] = 0;
}
}
}
return matrix;
}
public static void main(String[] args){
int[][] matrix = {{1,1,1},{1,0,1},{1,1,1}};
System.out.println("输入:" + Arrays.deepToString(matrix));
hot15_setZeroes hot15SetZeroes = new hot15_setZeroes();
int[][] result = hot15SetZeroes.setZeroes(matrix);
System.out.println("输出:" + Arrays.deepToString(result));
}
}