lintcode骑士的最短路线

lintcode 骑士的最短路线

描述

给定骑士在棋盘上的 初始 位置(一个2进制矩阵 0 表示空 1 表示有障碍物),找到到达 终点 的最短路线,返回路线的长度。如果骑士不能到达则返回 -1 。

说明

如果骑士的位置为 (x,y),他下一步可以到达以下这些位置:

(x + 1, y + 2)
(x + 1, y - 2)
(x - 1, y + 2)
(x - 1, y - 2)
(x + 2, y + 1)
(x + 2, y - 1)
(x - 2, y + 1)
(x - 2, y - 1)

样例

例1:

输入:
[[0,0,0],
[0,0,0],
[0,0,0]]
source = [2, 0] destination = [2, 2]
输出: 2
解释:
[2,0]->[0,1]->[2,2]
例2:

输入:
[[0,1,0],
[0,0,1],
[0,0,0]]
source = [2, 0] destination = [2, 2]
输出:-1

思路

使用一个队列来记录下第n步能够走到的所有的点,一个8*2的二维数组step来表示骑士的前进方式。

对于当前队列中的所有点,遍历step来得到所有的新的点,如果符合要求并且没有走过这个点,就可以加入到队列中并且把grid中该点变为true,在下一个循环中遍历该点。如果找到一个点是终点,那么返回步数。

代码

/**
 * Definition for a point.
 * struct Point {
 *     int x;
 *     int y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */

class Solution {
public:
    /**
     * @param grid: a chessboard included 0 (false) and 1 (true)
     * @param source: a point
     * @param destination: a point
     * @return: the shortest path 
     */
    int shortestPath(vector<vector<bool>> &grid, Point &source, Point &destination) {
        // write your code here
        vector<vector<int>> step = {{2,1},{1,2},{-2,1},{1,-2},{2,-1},{-1,2},{-1,-2},{-2,-1}};
        int n = grid.size(), m = grid[0].size(), res = 0;
        queue<Point> q;
        q.push(source);
        grid[source.x][source.y] = true;
        while (!q.empty()) {
            int N = q.size();
            res++;
            while (N > 0) {
                int r = q.front().x, c = q.front().y;
                N--;
                q.pop();
                if (r == destination.x && c == destination.y)
                    return res-1;
                for (int i = 0; i < step.size(); i++){
                    int new_r = r+step[i][0],
                        new_c = c+step[i][1];
                    if (new_r >= 0 && new_r < n && new_c >= 0 && new_c < m && !grid[new_r][new_c]) {
                        q.push(Point(new_r,new_c));
                        grid[new_r][new_c] = true;   
                    }
                }
            }
        }
        return -1;
        
    }
};

猜你喜欢

转载自blog.csdn.net/qq_40147449/article/details/88804015