Description

Given a _m _x _n _matrix, if an element is 0, set its entire row and column to 0. Do it in place.

Example

Given a matrix

[
  [1,2],
  [0,3]
],

return

[
[0,2],
[0,0]
]
Challenge

Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m+n) space, but still not the best solution.
Could you devise a constant space solution

Solution

用第一行和第一列来记录对应的行和列中有没有0值。
注意第一行和第一列要单独讨论。如果不单独讨论的话,比如第一行本来没有0,但是因为第j列有0,把(0, j)设成了0,再统一给matrix赋值的时候会把整个第一行都设成0。
所以要单独先记录下来第一行和第一列中有没有0.然后对剩下的矩阵中的数,把第一行和第一列单纯的作为flag来用。给剩下的矩阵中的数都进行了赋0的处理之后,再处理第一行和第一列。

public class Solution {
    /*
     * @param matrix: A lsit of lists of integers
     * @return: 
     */
    public void setZeroes(int[][] matrix) {
        // write your code here
        if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {
            return;
        }

        int n = matrix.length;
        int m = matrix[0].length;
        boolean zeroRow = false;
        for (int j = 0; j < m; j++) {
            if (matrix[0][j] == 0) {
                zeroRow = true;
                break;
            }
        }

        boolean zeroColumn = false;
        for (int i = 0; i < n; i++) {
            if (matrix[i][0] == 0) {
                zeroColumn = true;
                break;
            }
        }

        for (int i = 1; i < n; i++) {
            for (int j = 1; j < m; j++) {
                if (matrix[i][j] == 0) {
                    matrix[0][j] = 0;
                    matrix[i][0] = 0;
                }
            }
        }

        for (int i = 1; i < n; i++) {
            for (int j = 1; j < m; j++) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0) {
                    matrix[i][j] = 0;
                }
            }
        }

        if (zeroRow) {
            for (int j = 0; j < m; j++) {
                matrix[0][j] = 0;
            }
        }

        if (zeroColumn) {
            for (int i = 0; i < n; i++) {
                matrix[i][0] = 0;
            }
        }
    }
}

results matching ""

    No results matching ""