|
2 | 2 |
|
3 | 3 | /** |
4 | 4 | * |
5 | | - * @author chengfeili |
6 | | - * Jun 15, 2017 6:35:39 PM |
7 | | - * |
8 | | - * Problem: Write an algorithm such that if an element in an MxN matrix |
9 | | - * is 0, its entire row and column are set to 0. |
| 5 | + * Problem: Write an algorithm such that if an element in an MxN matrix is 0, |
| 6 | + * its entire row and column are set to 0. |
10 | 7 | * |
11 | | - * Solution: We can reduce the space to O(1) by using the first row as a |
12 | | - * replacement for the row array and the first column as a replacement |
13 | | - * for the column array. This works as follows: |
14 | | - * 1. Check if the first row and first column have any zeros, and set |
15 | | - * variables rowHasZero and columnHasZero. (We'll nullify the first row and |
16 | | - * first column later, if necessary.) |
17 | | - * 2. Iterate through the rest of the matrix, seeing matrix[i][0) and |
18 | | - * matrix[0) [j] to zero whenever there's a zero in |
19 | | - * matrix[i][j]. |
20 | | - * 3. Iterate through rest of matrix, nullifying row i if |
21 | | - * there's a zero in matrix[i][0]. |
22 | | - * 4. Iterate through rest of matrix, |
23 | | - * nullifying column j if there's a zero in matrix[ 0][ j]. |
24 | | - * 5. Nullify the first row and first column, if necessary (based on values from Step 1). |
| 8 | + * Solution: We can reduce the space to O(1) by using the first row as a |
| 9 | + * replacement for the row array and the first column as a replacement for the |
| 10 | + * column array. This works as follows: 1. Check if the first row and first |
| 11 | + * column have any zeros, and set variables rowHasZero and columnHasZero. (We'll |
| 12 | + * nullify the first row and first column later, if necessary.) 2. Iterate |
| 13 | + * through the rest of the matrix, seeing matrix[i][0) and matrix[0) [j] to zero |
| 14 | + * whenever there's a zero in matrix[i][j]. 3. Iterate through rest of matrix, |
| 15 | + * nullifying row i if there's a zero in matrix[i][0]. 4. Iterate through rest |
| 16 | + * of matrix, nullifying column j if there's a zero in matrix[ 0][ j]. 5. |
| 17 | + * Nullify the first row and first column, if necessary (based on values from |
| 18 | + * Step 1). |
25 | 19 | * |
26 | 20 | */ |
27 | 21 | public class ZeroMatrix { |
|
0 commit comments