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

  1. Enqueue the starting point and mark it.vis
  2. Dequeue and check if the destination is reached.
  3. Enumerate the four directions
  4. Valid, traversable, unvisited → Mark + Set predecessor + Enqueue
  5. Reach destination → backtrack path; queue empty before reaching destination → no solution

Output path step three

  1. Track predecessor:Write on enqueuepre[nr][nc] = {r, c}
  2. BackFrom the end point alongpreGo to Start
  3. Reverse output:Backtracking proceeds in reverse order; reverse before printing.

Common Mistakes

  • Mark upon enqueuevis
  • Record predecessor when enqueuing.
  • Reverse after backtracking
  • Set the endpoint to the coordinates provided in the problem.

Template

C++Copy
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
}
豫ICP备2026040576号-1