[LintCode] 1563. caminho mais curto para o destino

Dada uma matriz 2D representa as coordenadas no mapa, não são apenas os valores  0, 1, 2 no mapa. value 0 significa que ele pode passar,  value 1 meios não aceitável,  value 2 meios alvo lugar. A partir das coordenadas  [0,0], Você só pode ir para cima, baixo, esquerda e direita. Encontre o caminho mais curto que podem chegar ao destino, e devolver o comprimento do caminho.

Exemplo

Exemplo 1

Input:
[
 [0, 0, 0],
 [0, 0, 1],
 [0, 0, 2]
]
Output: 4
Explanation: [0,0] -> [1,0] -> [2,0] -> [2,1] -> [2,2]

exemplo 2

Input:
[
    [0,1],
    [0,1],
    [0,0],
    [0,2]
]
Output: 4
Explanation: [0,0] -> [1,0] -> [2,0] -> [3,0] -> [3,1]

público  classe Solution {
     / ** 
     * @param targetMap: 
     * @return : nada
      * / 
    público  int shortestPath ( int [] [] targetMap) {
         // Escreva o seu código aqui 
        Queue <celular> fila = new LinkedList <> ();
        int fileira = targetMap.length, col = targetMap [0 ] .length;
        boolean [] [] visitou = new  boolean [row] [col];
        int [] [] = instruções novo  int [] [] {{- 1, 0}, {1, 0}, {0, -1}, {0, 1}};
        int res = 0 ; 
        queue.offer ( novo celular (0, 0, targetMap [0] [0 ])); 
        visitou [ 0] [0] = verdadeiro ;
        enquanto (! queue.isEmpty ()) {
             int size = queue.size ();
            para ( int i = 0; i <tamanho; i ++ ) { 
                celular cur = queue.poll ();
                se (cur.value == 2 ) {
                     return res; 
                } 
                Para ( int[] Direcção: instruções) {
                     int nextrow = cur.row + direcção [0 ];
                    int NextCol = cur.col + direcção [1 ];
                    se (isValid (nextrow, NextCol, visitado, targetMap)) { 
                        queue.offer ( novo celular (nextrow, NextCol, targetMap [nextrow] [NextCol])); 
                        visitou [nextrow] [NextCol] = verdadeiro ; 
                    } 
                } 
            } 
            Res + = 1 ; 
        } 
        Retornar -1 ; 
    } 
    
    privado booleano isValid ( int nextrow, int NextCol, booleano [] [] visitado, int [] [] targetMap) {
         int fileira = targetMap.length, col = targetMap [0 ] .length;
        se (nextrow <0 || nextrow> = linha || NextCol <0 || NextCol> = col || visitou [nextrow] [NextCol]) {
             return  false ; 
        } 
        Retornar targetMap [nextrow] [NextCol] = 1! ; 
    } 
} 

Class celular {
     int row;
    int col;
    int value;
    públicoCelular ( int fileira, int col, int valor) {
         este .Row = fileira;
        este .col = col;
        este .value = valor; 
    } 
}

 

Acho que você gosta

Origin www.cnblogs.com/xuanlu/p/12446563.html
Recomendado
Clasificación