LintCode1563. Shortest path to the destination (BFS经典题)

原题如下:
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
Given:

[
[0, 0, 0],
[0, 0, 1],
[0, 0, 2]
]
Return: 4

Notice
1.The map must exist and is not empty, there is only one target

解法1:BFS.
注意:

  1. 此题类似骑士遍历题,但骑士遍历题的检查target是检查坐标,这题是检查value。所以如果在struct Point里面加上value这一项要确保target=2的值没有被改掉。
  2. 此题不需要visited map,因为可以简单的将targetMap[i][j]设为1,这样下次就不用再访问了。
  3. In the validPlace(), 要确保先检查p.x和p.y的范围,然后再检查grid[p.x][p.y]的值,不然就segment fault.

代码如下:

class Solution {
public:
    struct Point {
        int x;
        int y;
        Point(int row, int col) : x(row), y(col) {}
    };
    
    /**
     * @param targetMap: 
     * @return: nothing
     */
    int shortestPath(vector<vector<int>> &targetMap) {
        vector<int> dirX = {1, 0, -1, 0}; //east, north, west, south
        vector<int> dirY = {0, -1, 0, 1}; //east, north, west, south
     //   vector<vector<int>> visited(targetMap.size(), vector<int>(targetMap[0].size(), 0));

        queue<Point> q;
        q.push(Point(0, 0));
        int pathLen = 0;
        
        while(!q.empty()) {
            int qSize = q.size();
            for (int i = 0; i < qSize; ++i) {
                Point p = q.front();
                q.pop();
                
                if (targetMap[p.x][p.y] == 2) return pathLen;
                
                targetMap[p.x][p.y] = 1; //set as visited
                
                for (int j = 0; j < 4; ++j) {
                    Point neighborNode = Point(p.x + dirX[j], p.y + dirY[j]);
                    if (validPlace(targetMap, neighborNode)) 
                        q.push(neighborNode);
                }
            }
            pathLen++;
        }
        
        return -1;
    }

private:
    bool validPlace(vector<vector<int>> &grid, Point &p) {
        return (p.x >= 0 && p.x < grid.size() && p.y >= 0 && p.y < grid[0].size()) &&
               (grid[p.x][p.y] >= 0) &&
               (grid[p.x][p.y] != 1);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值