490. The Maze(BFS模板)
注意:本题要求一个方向需要走到底算一步。
class Solution {
vector<int> dx = {0, -1, 0, 1}, dy = {1, 0, -1, 0};
public:
bool hasPath(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
int n = maze.size(), m = maze[0].size();
vector<vector<bool>> visited(n, vector<bool>(m));
queue<pair<int, int>> q;
q.push({start[0], start[1]});
while (!q.empty()) {
pair<int, int> cur = q.front();
q.pop();
if (cur.first == destination[0] && cur.second == destination[1]) return true;
for (int i = 0; i < 4; i ++ ) {
int x = cur.first, y = cur.second;
while (x + dx[i] >= 0 && x + dx[i] < n && y + dy[i] >= 0 && y + dy[i] < m &&
maze[x + dx[i]][y + dy[i]] == 0) {
x += dx[i]; y += dy[i];
}
if (make_pair(x, y) != cur) {
if (visited[x][y]) continue;
q.push({x, y});
visited[x][y] = true;
}
}
}
return false;
}
};
505. The Maze II(Dijkstra模板)
Link
Dijkstra用于计算无负权边的单源最短路。
相比于BFS模板,Dijkstra使用priority_queue使队列中的点按照与起点的距离排序。并使用solved标记已经确定最短距离的节点,而不是BFS中用visited标记已经访问过的节点。没有被solved的节点的distance可能被当前节点更新,所以更新distance后加入优先队列pq(优先队列会自动将distance较小的放在前面)。
另外,由于节点可能被重复加入优先队列,所以当我们从pq中取出节点时,如果它已经被solved,就跳过。
struct Node {
int x, y, distance;
Node(int x, int y, int distance) : x(x), y(y), distance(distance) {}
bool operator<(const Node& a) const {return distance > a.distance; }
};
class Solution {
vector<int> dx = {0, -1, 0, 1}, dy = {1, 0, -1, 0};
public:
int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
int n = maze.size(), m = maze[0].size();
vector<vector<bool>> solved(n, vector<bool>(m, false));
priority_queue<Node> pq;
pq.push(Node(start[0], start[1], 0));
while (!pq.empty()) {
Node node = pq.top();
pq.pop();
if (node.x == destination[0] && node.y == destination[1]) return node.distance;
// There might be multiple nodes with the same {x, y} but different {distance} in pq.
// Skip ones which are already solved.
if (solved[node.x][node.y]) continue;
solved[node.x][node.y] = true;
for (int i = 0; i < 4; ++i) {
int numSteps = 0;
int x = node.x, y = node.y;
while (x + dx[i] >= 0 && x + dx[i] < n && y + dy[i] >= 0 && y + dy[i] < m &&
maze[x + dx[i]][y + dy[i]] == 0) {
x += dx[i]; y += dy[i];
numSteps++;
}
if (solved[x][y]) continue;
pq.push(Node(x, y, node.distance + numSteps));
}
}
return -1;
}
};