首页 > 代码库 > 1.7 Matrix Zero
1.7 Matrix Zero
Write an algorithm such that if an element in an MxN matrix is 0, its
entire rowand column are set to 0.
1 public static void matrixZero(int[][] matrix) { 2 if (matrix.length == 0 || matrix[0].length == 0) 3 return; 4 5 int m = matrix.length; 6 int n = matrix[0].length; 7 boolean rowZero = false; 8 boolean colZero = false; 9 10 // save first row and first col11 for (int i = 0; i < m; i++)12 if (matrix[i][0] == 0)13 rowZero = true;14 for (int i = 0; i < n; i++)15 if (matrix[0][i] == 0)16 colZero = true;17 18 for (int i = 0; i < m; i++) {19 for (int j = 0; j < n; j++) {20 if (matrix[i][j] == 0) {21 matrix[i][0] = 0;22 matrix[0][j] = 0;23 }24 }25 }26 27 for (int i = 1; i < m; i++) {28 if (matrix[i][0] == 0)29 for (int j = 1; j < n; j++) {30 matrix[i][j] = 0;31 }32 }33 34 for (int i = 1; i < n; i++) {35 if (matrix[0][i] == 0)36 for (int j = 1; j < m; j++) {37 matrix[j][i] = 0;38 }39 }40 41 if (rowZero) {42 for (int i = 0; i < m; i++)43 matrix[i][0] = 0;44 }45 46 if (colZero) {47 for (int i = 0; i < n; i++)48 matrix[0][i] = 0;49 }50 }
1.7 Matrix Zero
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。