深度优先搜索进阶4-广搜输出路径

· · 个人记录

课堂练习

T628045 迷宫问题

代码与注释

#include<bits/stdc++.h>
using namespace std;

// 方向数组:右、下、左、上
long long dx[] = {1, 0, -1, 0};
long long dy[] = {0, 1, 0, -1};

// s数组存储每个点到起点的最短距离,初始化为100(表示无穷大)
long long s[10][10] = {100}; 

// ax和ay数组存储路径中各点的坐标
long long ax[100], ay[100];

// 地图和访问标记数组
char mp[1000][1000];
bool vis[1000][1000];

// 标记是否找到路径
bool flag;

// 节点结构体:x,y坐标,b表示步数
struct node {
    long long x, y, b;
};

// 深度优先搜索:用于回溯路径
void dfs(long long x, long long y) {
    if(flag) return;  // 如果已经找到路径,直接返回

    // 到达起点,标记找到路径
    if(x == 0 && y == 0) {
        flag = 1;
        return;
    }

    // 尝试四个方向
    for(long long i = 0; i < 4; i++) {
        long long xx = x + dx[i];
        long long yy = y + dy[i];

        // 检查边界
        if(xx >= 0 && xx < 5 && yy >= 0 && yy < 5) {
            // 如果当前点的距离比下一个点大1,或者下一个点是起点
            if((s[x][y] > 1 && s[xx][yy] == s[x][y] - 1) || s[xx][yy] == 100) {
                // 记录路径
                ax[s[xx][yy]] = xx;
                ay[s[xx][yy]] = yy;
                dfs(xx, yy);
            }
        }
    }
}

// 广度优先搜索:寻找最短路径
void bfs() {
    queue<node> q;
    q.push({0, 0, 0});  // 起点入队
    vis[0][0] = 1;      // 标记起点已访问
    s[0][0] = 0;        // 起点距离为0

    while(q.size()) {
        node f = q.front();
        q.pop();

        // 到达终点
        if(f.x == 4 && f.y == 4) {
            // 回溯路径
            dfs(4, 4);

            // 输出路径
            for(long long i = 0; i < s[4][4]; i++) {
                cout << '(' << ax[i] << ", " << ay[i] << ")\n";
            }
            cout << "(4, 4)";
            return;
        }

        // 尝试四个方向
        for(long long i = 0; i < 4; i++) {
            long long xx = f.x + dx[i];
            long long yy = f.y + dy[i];

            // 检查边界、是否是墙、是否已访问
            if(xx >= 0 && xx < 5 && yy >= 0 && yy < 5 && mp[xx][yy] != '1' && !vis[xx][yy]) {
                vis[xx][yy] = 1;            // 标记已访问
                s[xx][yy] = f.b + 1;        // 记录距离
                q.push({xx, yy, f.b + 1});  // 入队
            }
        }
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    // 读入地图
    for(long long i = 0; i < 5; i++) {
        for(long long j = 0; j < 5; j++) {
            cin >> mp[i][j];
        }
    }

    // 初始化s数组
    for(int i = 0; i < 10; i++) {
        for(int j = 0; j < 10; j++) {
            s[i][j] = 100;
        }
    }

    // 执行BFS搜索
    bfs();

    return 0;
}

T628044 迷宫之输出路径-困难版

代码与注释

#include<bits/stdc++.h>
using namespace std;

// 定义节点结构体,存储坐标和步数
struct node {
    long long x, y, step; // x,y坐标,step表示步数
};

// 全局变量定义
long long n, m; // 迷宫的行数和列数
long long dx[4] = {1, 0, 0, -1}; // 四个方向的x变化量(D,L,R,U)
long long dy[4] = {0, -1, 1, 0}; // 四个方向的y变化量
char dir[4] = {'D', 'L', 'R', 'U'}; // 对应的方向字符(按字典序排列)
char mp[1000][1000]; // 存储迷宫地图
bool vis[1000][1000]; // 访问标记数组
string path[1000][1000]; // 存储到每个点的最短路径

// 广度优先搜索函数
void bfs() {
    // 检查起点是否是障碍物
    if(mp[1][1] == '1') {
        return;
    }

    queue<node> q;
    q.push({1, 1, 0}); // 起点入队
    path[1][1] = ""; // 起点的路径为空字符串
    vis[1][1] = 1; // 标记起点已访问

    while(!q.empty()) {
        node f = q.front();
        q.pop();

        // 如果到达终点,直接返回
        if(f.x == n && f.y == m) {
            return;
        }

        // 尝试四个方向(按D,L,R,U的顺序,保证字典序最小)
        for(long long i = 0; i < 4; i++) {
            int xx = f.x + dx[i];
            int yy = f.y + dy[i];

            // 检查新位置是否合法且未被访问过
            if(xx > 0 && yy > 0 && xx <= n && yy <= m && 
               mp[xx][yy] == '0' && !vis[xx][yy]) {
                // 新位置入队
                q.push({xx, yy, f.step + 1});
                // 标记已访问
                vis[xx][yy] = 1;
                // 更新路径:当前路径加上新方向
                path[xx][yy] = path[f.x][f.y] + dir[i];
            }
        }
    }
}

int main() {
    // 输入迷宫大小
    cin >> n >> m;

    // 输入迷宫地图
    for(long long i = 1; i <= n; i++) {
        for(long long j = 1; j <= m; j++) {
            cin >> mp[i][j];
        }
    }

    // 执行BFS搜索
    bfs();

    // 输出结果
    if(!vis[n][m]) {
        // 如果终点未被访问,说明无解
        cout << -1 << endl;
    } else {
        // 输出到终点的最短路径
        cout << path[n][m] << endl;
    }

    return 0;
}

P2360 地下城主

代码与注释

#include<bits/stdc++.h>
using namespace std;

// 定义地牢的层数、行数、列数
int L, R, C;

// 三维数组存储地牢地图
char mp[40][40][40]; // mp[y][x][z] 注意坐标顺序

// 访问标记数组
bool vis[40][40][40];

// 起点坐标
int sx, sy, sz;

// 六个方向的移动增量:右、左、前、后、上、下
int dx[] = {0, 0, 0, 0, 1, -1}; // x轴变化
int dy[] = {1, -1, 0, 0, 0, 0};  // y轴变化
int dz[] = {0, 0, 1, -1, 0, 0};  // z轴变化

// 节点结构体:存储坐标和步数
struct node {
    int x, y, z, step;
};

// 广度优先搜索函数
void bfs() {
    queue<node> q;
    q.push({sx, sy, sz, 0}); // 起点入队,步数为0
    vis[sy][sx][sz] = 1;     // 标记起点已访问

    while (!q.empty()) {
        node f = q.front();
        q.pop();

        // 如果到达终点
        if (mp[f.y][f.x][f.z] == 'E') {
            cout << "Escaped in " << f.step << " minute(s)." << endl;
            return;
        }

        // 尝试六个方向
        for (int i = 0; i < 6; i++) {
            int nx = f.x + dx[i]; // 新x坐标
            int ny = f.y + dy[i]; // 新y坐标
            int nz = f.z + dz[i]; // 新z坐标

            // 检查新位置是否合法
            if (nx >= 1 && nx <= C &&    // x在列范围内
                ny >= 1 && ny <= R &&    // y在行范围内
                nz >= 1 && nz <= L &&    // z在层范围内
                mp[ny][nx][nz] != '#' && // 不是岩石
                !vis[ny][nx][nz]) {      // 未被访问

                vis[ny][nx][nz] = 1; // 标记已访问
                q.push({nx, ny, nz, f.step + 1}); // 新位置入队,步数+1
            }
        }
    }

    // 如果队列空仍未找到终点
    cout << "Trapped!" << endl;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    // 输入地牢层数、行数、列数
    cin >> L >> R >> C;

    // 读取地牢地图
    for (int z = 1; z <= L; z++) {       // 逐层读取
        for (int y = 1; y <= R; y++) {   // 逐行读取
            string line;
            cin >> line; // 读取一行
            for (int x = 1; x <= C; x++) {
                mp[y][x][z] = line[x-1]; // 存储每个格子

                // 记录起点坐标
                if (mp[y][x][z] == 'S') {
                    sx = x;
                    sy = y;
                    sz = z;
                }
            }
        }
        // 跳过层之间的空行(除了最后一层)
        if (z < L) {
            cin.ignore(); // 忽略换行符
        }
    }

    // 执行BFS搜索
    bfs();

    return 0;
}

家庭作业

D3443 【提高】走出迷宫的最短路径

AC代码

#include<bits/stdc++.h>
using namespace std;

const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, 1, 0, -1};

struct Point {
    int x, y;
};

bool BFS(vector<vector<int>>& maze, Point start, Point end, 
         vector<vector<Point>>& prev, vector<vector<bool>>& visited) {
    int n = maze.size();
    int m = maze[0].size();

    queue<Point> q;
    q.push(start);
    visited[start.x][start.y] = true;
    prev[start.x][start.y] = {-1, -1};

    while (!q.empty()) {
        Point current = q.front();
        q.pop();

        if (current.x == end.x && current.y == end.y) {
            return true;
        }

        for (int i = 0; i < 4; i++) {
            int nx = current.x + dx[i];
            int ny = current.y + dy[i];

            if (nx >= 0 && nx < n && ny >= 0 && ny < m && 
                maze[nx][ny] == 0 && !visited[nx][ny]) {
                visited[nx][ny] = true;
                prev[nx][ny] = current;
                q.push({nx, ny});
            }
        }
    }
    return false;
}

vector<Point> getPath(Point start, Point end, vector<vector<Point>>& prev) {
    vector<Point> path;
    Point current = end;

    while (!(current.x == -1 && current.y == -1)) {
        path.push_back(current);
        current = prev[current.x][current.y];
    }

    reverse(path.begin(), path.end());
    return path;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n, m;
    cin >> n >> m;
    vector<vector<int>> maze(n, vector<int>(m));
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> maze[i][j];
        }
    }

    int s1, s2, e1, e2;
    cin >> s1 >> s2;
    cin >> e1 >> e2;

    Point start = {s1-1, s2-1};
    Point end = {e1-1, e2-1};

    if (start.x < 0 || start.x >= n || start.y < 0 || start.y >= m || 
        end.x < 0 || end.x >= n || end.y < 0 || end.y >= m ||
        maze[start.x][start.y] == 1 || maze[end.x][end.y] == 1) {
        cout << "no way";
        return 0;
    }

    vector<vector<bool>> visited(n, vector<bool>(m, false));
    vector<vector<Point>> prev(n, vector<Point>(m, {-1, -1}));

    bool found = BFS(maze, start, end, prev, visited);

    if (!found) {
        cout << "no way";
    } else {
        vector<Point> path = getPath(start, end, prev);

        for (int i = 0; i < path.size(); i++) {
            cout << "(" << path[i].x+1 << "," << path[i].y+1 << ")";
            if (i < path.size()-1) {
                cout << "->";
            }
        }
    }

    return 0;
}

P1443 马的遍历

AC代码

#include<bits/stdc++.h>
using namespace std;
long long n,m,x2,y2,vis[1000][1000],dx[]={-1,1,2,2,1,-1,-2,-2},dy[]={-2,-2,-1,1,2,2,1,-1},mp[1000][1000];
struct node{
    long long x,y,b;
};
void bfs(){
    queue<node>q;
    q.push({x2,y2,0});
    while(q.size()){
        node f=q.front();
        q.pop();
        vis[f.x][f.y]=1;
        mp[f.x][f.y]=f.b;
        for(long long i=0;i<8;i++){
            long long xx=f.x+dx[i], yy=f.y+dy[i];
            if(xx>0&&yy>0&&xx<=n&&yy<=m&&vis[xx][yy]==0){
                q.push({xx,yy,f.b+1});
                vis[xx][yy]=1;
            }
        }
    }
}
int main(){
    cin>>n>>m>>x2>>y2;
    for(long long i=1;i<=n;i++){
        for(long long j=1;j<=m;j++){
            mp[i][j]=-1;
        }
    }
    bfs();
    for(long long i=1;i<=n;i++){
        for(long long j=1;j<=m;j++){
            cout<<mp[i][j]<<' ';
        }
        cout<<'\n';
    }
    return 0;
}

P1699 [USACO19OPEN] Bucket Brigade B

AC代码

#include<bits/stdc++.h>
using namespace std;
char s[1010][1010];
long long dx[]={0,-1,0,1},dy[]={-1,0,1,0},vis[1010][1010],n=10,m=10,sx,sy,tx,ty;
struct node{
    long long x,y,step;
};
int bfs(long long sx,long long sy,long long tx,long long ty){
    queue<node>q;
    q.push({sx,sy,0});
    while(q.size()){
        node f=q.front();
        q.pop();
        for(int i=0;i<4;i++){
            long long xx=f.x+dx[i],yy=f.y+dy[i];
            if(xx<0||xx>=n||yy<0||yy>=m||vis[xx][yy]==1||s[xx][yy]=='R'){
                continue;
            }
            vis[xx][yy]=1;
            q.push({xx,yy,f.step+1});
            if(xx==tx&&yy==ty){
                return f.step;
            }
        }
    }
    return -1;
}
int main(){
    for(long long i=0;i<n;i++){
        for(int j=0;j<m;j++){
            cin>>s[i][j];
            if(s[i][j]=='L'){
                sx=i;
                sy=j;
            }
            if(s[i][j]=='B'){
                tx=i;
                ty=j;
            }
        }
    }
    vis[sx][sy]=1;
    cout<<bfs(sx,sy,tx,ty);;
}