Java for LeetCode 073 Set Matrix Zeroes

时间:2023-03-08 17:34:26

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

解题思路:

用两个boolean数组row col表示行列是否有零即可,JAVA实现如下:

	public void setZeroes(int[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0)
return;
boolean[] row = new boolean[matrix.length], col = new boolean[matrix[0].length];
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[0].length; j++)
if (matrix[i][j] == 0) {
row[i] = true;
col[j] = true;
}
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++)
if (row[i] || col[j])
matrix[i][j] = 0;
}