使用路径跟踪进行广度优先搜索,某些坐标被“跳过”

时间:2016-09-09 04:52:59

标签: c++ algorithm

我正在网格上编写广度优先搜索实现,其附加功能是跟踪从终点返回到起点的路径。广度优先搜索算法按预期工作,但我在跟踪路径时遇到问题。它以某种方式“跳过”某些坐标。

考虑这个示例输入:

3 3 //Grid Dimension (Row Column)
S|E //'S' = Start Point, 'E' = End Point
... //'.' = Empty Space, '|' = Wall
...

我希望输出为:

Shortest Distance to the End Point: 4
Shortest Path Route:
X|X
XXX
...

但我的计划却给了我:

Shortest Distance to the End Point: 4
Shortest Path Route:
S|X
XX.
...

我确保位置和原点是正确的。首先,在BFS算法内部,我打印出每个点的原点。其次,在路径跟踪算法中,我打印出当前坐标是什么,该点的起源是什么。这是我打印出来的:

//First debug: Inside BFS
The origin for (1, 0) is (0, 0)
The origin for (1, 1) is (1, 0)
The origin for (2, 0) is (1, 0)
The origin for (1, 2) is (1, 1)
The origin for (2, 1) is (1, 1)
The origin for (0, 2) is (1, 2)
The origin for (2, 2) is (1, 2)

//Second Debug: Inside Path Trace
From (0, 2) going to the origin, which is (1, 2)
From (1, 1) going to the origin, which is (1, 0)
From (1, 0) going to the origin, which is (0, 0)

问题是,(1, 2)在路径跟踪中被跳过了。但是,它认为(1, 2)的来源是下一个点,即(1, 1)

我的代码中没有看到任何错误(至少在BFS中它正常工作),所以这里是我编码的路径跟踪功能:

//On every point, I initially set the origin to be (-1, -1)
//Through the BFS, each point set its own origin
//If it is certain that there's a path from the Start Point to the End Point,
//Then from the End Point, I can traverse the origin until I reach (-1, -1)

coordinate currentPoint = endPoint;
while ((currentPoint.row != -1) && (currentPoint.col != -1)) {
        map[currentPoint.row][currentPoint.col] = 'X';
        currentPoint.row = mapData[currentPoint.row][currentPoint.col].origin.row;
        currentPoint.col = mapData[currentPoint.row][currentPoint.col].origin.col;
}

对此有何看法?感谢

1 个答案:

答案 0 :(得分:3)

在这些方面:

    currentPoint.row = mapData[currentPoint.row][currentPoint.col].origin.row;
    currentPoint.col = mapData[currentPoint.row][currentPoint.col].origin.col;

您正在更改第一行中currentPoint.row的值,然后在第二行中使用它。这意味着你得到(1,2)的col而不是(0,2)

类似的东西:

    int newRow = mapData[currentPoint.row][currentPoint.col].origin.row;
    int newCol = mapData[currentPoint.row][currentPoint.col].origin.col;
    mapData[currentPoint.row][currentPoint.col].origin.row = newRow;
    mapData[currentPoint.row][currentPoint.col].origin.col = newCol

会解决它。