[LintCode] 1563. Shortest path to the destination

Given a 2D array representing the coordinates on the map, there are only values 0, 1, 2 on the map. value 0 means that it can pass, value 1 means not passable, value 2 means target place. Starting from the coordinates [0,0],You can only go up, down, left and right. Find the shortest path that can reach the destination, and return the length of the path.

Example

Example 1

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

Example 2

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

public class Solution {
    /**
     * @param targetMap: 
     * @return: nothing
     */
    public int shortestPath(int[][] targetMap) {
        // Write your code here
        Queue<Cell> queue = new LinkedList<>();
        int row = targetMap.length, col = targetMap[0].length;
        boolean[][] visited = new boolean[row][col];
        int[][] directions = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        int res = 0;
        queue.offer(new Cell(0, 0, targetMap[0][0]));
        visited[0][0] = true;
        while(!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                Cell cur = queue.poll();
                if (cur.value == 2) {
                    return res;
                }
                for (int[] direction: directions) {
                    int nextRow = cur.row + direction[0];
                    int nextCol = cur.col + direction[1];
                    if (isValid(nextRow, nextCol, visited, targetMap)) {
                        queue.offer(new Cell(nextRow, nextCol, targetMap[nextRow][nextCol]));
                        visited[nextRow][nextCol] = true;
                    }
                }
            }
            res += 1;
        }
        return -1;
    }
    
    private boolean isValid(int nextRow, int nextCol, boolean[][] visited, int[][] targetMap) {
        int row = targetMap.length, col = targetMap[0].length;
        if (nextRow < 0 || nextRow >= row || nextCol < 0 || nextCol >= col || visited[nextRow][nextCol]) {
            return false;
        }
        return targetMap[nextRow][nextCol] != 1;
    }
}

class Cell {
    int row;
    int col;
    int value;
    public Cell(int row, int col, int value) {
        this.row = row;
        this.col = col;
        this.value = value;
    }
}

 

posted @ 2020-03-09 04:37  xuan_abc  阅读(241)  评论(0编辑  收藏  举报