Problem Statement and Algorithm DescriptionDocument Reading
Problem Statement and Algorithm Description
BFS Shortest Path Cheat Sheet
C++ Algorithm Principles1.2 KBUploaded on2026/10/14 12:15
BFS Shortest Path · One-Page Cheat Sheet
Core:Use a queue to expand layer by layer; the first time the destination is reached, it's the shortest path.
Steps
- Enqueue the starting point and mark it.
vis - Dequeue and check if the destination is reached.
- Enumerate the four directions
- Valid, traversable, unvisited → Mark + Set predecessor + Enqueue
- Reach destination → backtrack path; queue empty before reaching destination → no solution
Output path step three
- Track predecessor:Write on enqueue
pre[nr][nc] = {r, c} - BackFrom the end point along
preGo to Start - Reverse output:Backtracking proceeds in reverse order; reverse before printing.
Common Mistakes
- Mark upon enqueue
vis - Record predecessor when enqueuing.
- Reverse after backtracking
- Set the endpoint to the coordinates provided in the problem.
Template
vis[sr][sc]=1; pre[sr][sc]={-1,-1}; q.push({sr,sc});
while(!q.empty()){
auto [r,c]=q.front(); q.pop();
if(r==er&&c==ec) break;
for(4方向){
if(合法&&!vis&&可走){
vis[nr][nc]=1;
pre[nr][nc]={r,c};
q.push({nr,nc});
}
}
}
if(!vis[er][ec]) cout<<No way;
else{
vector<point> p;
for(int r=er,c=ec;!(r==-1&&c==-1);){
p.push_back({r,c});
auto [pr,pc]=pre[r][c]; r=pr; c=pc;
}
reverse(p.begin(),p.end());
// Output p
}