java bfs 20ms 96%


  • 0
    public int[][] updateMatrix(int[][] matrix) {
            int n = matrix.length;
            int i = 0;
            boolean change = check(matrix,++i);
            while(change) {    
                change = check(matrix,++i);
            }
            return matrix;
        }
        private boolean check(int[][] matrix,int l) {
            boolean change = false;
            int m = matrix.length;
            int n = matrix[0].length;
            for(int i = 0;i < m;i++) {
                for(int j = 0;j < n;j++) {
                    if(matrix[i][j] == 0) continue;
                    if( (i == 0 || matrix[i - 1][j] >= l) && (i == m - 1 || matrix[i + 1][j] >= l) &&
                        (j == 0 || matrix[i][j - 1] >= l) && (j == n - 1 || matrix[i][j + 1] >= l) ) {
                        matrix[i][j] = l + 1;
                        change = true;
                    }
                }
            }
            return change;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.