示例 1:
输入:matrix = [[1,1,1],[1,0,1],[1,1,1]]
输出:[[1,0,1],[0,0,0],[1,0,1]]
public class ZeroMatrix {
public static void setZeroes(int[][] matrix) {
boolean firstRowZero = false;
boolean firstColZero = false;
// 检查第一行是否有0
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[0][j] == 0) {
firstRowZero = true;
break;
}
}
// 检查第一列是否有0
for (int i = 0; i < matrix.length; i++) {
if (matrix[i][0] == 0) {
firstColZero = true;
break;
}
}
// 使用第一行和第一列来记录其他行列是否需要置0
for (int i = 1; i < matrix.length; i++) {
for (int j = 1; j < matrix[0].length; j++) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
// 根据记录,置0其他行列
for (int i = 1; i < matrix.length; i++) {
for (int j = 1; j < matrix[0].length; j++) {
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
matrix[i][j] = 0;
}
}
}
// 根据标记决定是否将第一行置为0
if (firstRowZero) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[0][j] = 0;
}
}
// 根据标记决定是否将第一列置为0
if (firstColZero) {
for (int i = 0; i < matrix.length; i++) {
matrix[i][0] = 0;
}
}
}
public static void main(String[] args) {
int[][] matrix = {
{
1, 2, 3, 4},
{
5, 0, 7, 8},
{
9, 10, 11, 12},
{
0, 14, 15, 16}
};
System.out.println("原始矩阵:");
printMatrix(matrix);
setZeroes(matrix);
System.out.println("\n置零后的矩阵:");
printMatrix(matrix);
}
public static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
}
}
更多【算法-【矩阵】73. 矩阵置零【中等】】相关视频教程:www.yxfzedu.com