1 public class Solution { 2 public void setZeroes(int[][] matrix) { 3 int m=matrix.length; 4 int n=matrix[0].length; 5 boolean hasZeroCol = false, hasZeroRow = false; 6 7 for (int i=0; i<m; i++) 8 if (matrix[i][0] == 0) { hasZeroCol = true; break; } 9 10 for (int j=0; j<n; j++) 11 if (matrix[0][j] == 0) { hasZeroRow = true; break; } 12 13 for (int i=1; i<m; i++) { 14 for (int j=1; j<n; j++) { 15 if (matrix[i][j] == 0) { 16 matrix[0][j] = 0; 17 matrix[i][0] = 0; 18 } 19 } 20 } 21 22 for (int i=1; i<m; i++) { 23 for (int j=1; j<n; j++) { 24 if (matrix[i][0] == 0 || matrix[0][j] == 0) 25 matrix[i][j] = 0; 26 } 27 } 28 29 if (hasZeroCol) 30 for (int i=0; i<m; i++) matrix[i][0] = 0; 31 32 if (hasZeroRow) 33 for (int i=0; i<n; i++) matrix[0][i] = 0; 34 35 36 } 37 }
时间: 2024-10-06 17:06:24