LeetCode: Set Matrix Zeroes

Java:

需要注意的是,题目要求不能有额外的空间,因此我们需要在矩阵上进行操作,不能直接将行和列置0,因此我们需要存储各行列的状态,但是首行首列的状态不能存在matrix[0][0]中,需要两个boolean变量来存储,而这两个boolean变量的初值则是matrix[0][0] == 0

 1 public class Solution {
 2     public void setZeroes(int[][] matrix) {
 3         int m = matrix.length;
 4         int n = matrix[0].length;
 5         boolean rowZero = matrix[0][0] == 0;
 6         boolean columnZero = matrix[0][0] == 0;
 7         for (int i = 1; i < m; i++) {
 8             if (matrix[i][0] == 0) {
 9                 columnZero = true;
10                 break;
11             }
12         }
13         for (int i = 1; i < n; i++) {
14             if (matrix[0][i] == 0) {
15                 rowZero = true;
16                 break;
17             }
18         }
19         for (int i = 1; i < m; i++) {
20             for (int j = 1; j < n; j++) {
21                 if (matrix[i][j] == 0) {
22                     matrix[i][0] = 0;
23                     matrix[0][j] = 0;
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++) matrix[i][j] = 0;
30             }
31         }
32         for (int j = 1; j < n; j++) {
33             if (matrix[0][j] == 0) {
34                 for (int i = 1; i < m; i++) matrix[i][j] = 0;
35             }
36         }
37         if (rowZero == true) {
38             for (int j = 0; j < n; j++) matrix[0][j] = 0;
39         }
40         if (columnZero == true) {
41             for (int i = 0; i < m; i++) matrix[i][0] = 0;
42         }
43     }
44 }
原文地址:https://www.cnblogs.com/yingzhongwen/p/3033423.html