Golden programmer interview - face questions 01.08 zero matrix

topic:

Preparation of an algorithm, when an M × N matrix elements are 0, then the rows and columns it is cleared.

 

Example 1:

Input:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
Output:
[
[1,0,1],
[0,0,0],
[0 , 1]
]
example 2:

Input:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
Output:
[
[0,0,0,0],
[0,4 , 5,0],
[0,3,1,0]
]

analysis:

Finds the first row 0, and with this line need to store empty row after each traversed line, if not at the same time need to clear diverted to the marked line then can be directly cleared.

program:

class Solution {
    public void setZeroes(int[][] matrix) {
        int row = -1;
        boolean delr = false;
        for(int i = 0; i < matrix.length; ++i){
            for(int j = 0; j < matrix[i].length; ++j){
                if(matrix[i][j] == 0){
                    row = i;
                    break;
                }
            }
            if(row != -1)
                break;
        }
        if(row == -1)
            return;
        for(int i = 0; i < matrix.length; ++i){
            for(int j = 0; j < matrix[i].length; ++j){
                if(matrix[i][j] == 0){
                    delr = true;
                    matrix[row][j] = 0;
                }
            }
            if(i != row && delr){
                for(int k = 0; k < matrix[i].length; ++k){
                    matrix[i][k] = 0;
                }
            }
            delr = false;
        }
        for(int i = 0; i < matrix[row].length; ++i){
            if(matrix[row][i] == 0){
                for(int j = 0; j < matrix.length; ++j){
                    matrix[j][i] = 0;
                }
            }else{
                matrix[row][i] = 0;
            }
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/silentteller/p/12395962.html