Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

Solution: 每遇到一个0,就把它所在行和列的第一个元素置为0,同时用2个flag记录第一行和第一列是否有0

    public void setZeroes(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0] == null || grid[0].length == 0) {
            return;
        }
        int m = grid.length, n = grid[0].length;
        boolean first_row = false, first_column = false;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 0) {
                    if (i == 0) {
                        first_row = true;
                    }
                    if (j == 0) {
                        first_column = true;
                    }
                    grid[i][0] = 0;
                    grid[0][j] = 0;
                }
            }
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (grid[i][0] == 0 || grid[0][j] == 0) {
                    grid[i][j] = 0;
                }
            }
        }
        if (first_row) {
            for (int j = 0; j < n; j++) {
                grid[0][j] = 0;
            }
        }
        if (first_column) {
            for (int i = 0; i < m; i++) {
                grid[i][0] = 0;
            }
        }
    }

results matching ""

    No results matching ""