原题如下:
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.
注意:
- 此题类似骑士遍历题,但骑士遍历题的检查target是检查坐标,这题是检查value。所以如果在struct Point里面加上value这一项要确保target=2的值没有被改掉。
- 此题不需要visited map,因为可以简单的将targetMap[i][j]设为1,这样下次就不用再访问了。
- 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);
}
};