Bootstrap

深度优先搜索(DFS)无向图寻找路径

在无向图上寻找1~8的路径

一.测试案例

输入:

请输入节点数和边数: 9 10
请输入每条边(格式:u v 表示边 u -> v): 
1 2
1 3
2 4
2 5
3 6
3 7
4 8
5 8
6 8
7 8
请输入起点和终点: 
1 8

 输出:

找到路径: 1 2 4 8

二.源代码

#include <iostream>
#include <vector>

using namespace std;

const int MAX_LEN = 100; // 最大结点数,假设图中结点不超过100个

// 定义节点路径的结构
int path[MAX_LEN]; // 用来记录从起点到终点的路径
bool visited[MAX_LEN]; // 标记结点是否被访问过
int depth; // 深度,表示当前路径长度,起点深度为0

// 图的邻接表表示
vector<int> adj[MAX_LEN]; // 邻接表

// 深度优先搜索
bool dfs(int v, int target) {
    path[depth] = v; // 记录当前节点
    if (v == target) {
        return true; // 找到目标节点,直接返回
    }
    if (visited[v]) {
        return false; // 如果节点已经访问过,避免回环
    }

    visited[v] = true; // 将节点标记为已访问
    ++depth; // 增加路径深度

    // 遍历当前节点的所有邻接节点
    for (int u : adj[v]) {
        if (dfs(u, target)) {
            return true; // 如果递归能到达终点,返回true
        }
    }

    // 如果没有找到路径,回溯
    --depth; // 回退路径深度
    visited[v] = false; // 标记为未访问
    return false;
}

int main() {
    int n, m; // n是节点数,m是边数
    cout << "请输入节点数和边数: ";
    cin >> n >> m;

    // 输入图的边
    cout << "请输入每条边(格式:u v 表示边 u -> v): " << endl;
    for (int i = 0; i < m; ++i) {
        int u, v;
        cin >> u >> v;
        adj[u].push_back(v); // 记录从u到v的边
        adj[v].push_back(u); // 如果是无向图,需要添加从v到u的边
    }

    // 初始化
    for (int i = 0; i < n; ++i) {
        visited[i] = false;
    }

    int start, target;
    cout << "请输入起点和终点: ";
    cin >> start >> target;

    // 初始化路径深度
    depth = 0;

    // 从起点出发,寻找从start到target的路径
    if (dfs(start, target)) {
        cout << "找到路径: ";
        for (int i = 0; i <= depth; ++i) { // 需要包括终点
            cout << path[i] << " ";
        }
        cout << endl;
    } else {
        cout << "没有找到路径" << endl;
    }

    return 0;
}

;