深度优先搜索找到目标节点的路径

//题目:深度优先搜索
//
//给定一个无向图,使用深度优先搜索算法找到从给定起始节点到目标节点的路径。
//
//问题函数定义:
//
//cpp
//vector<int> dfs(vector<vector<int>>& graph, int start, int target);
//裁判测试程序样例:
//
//cpp
#include<iostream>
#include<stack>
#include <vector>
#include<string>
#include<algorithm>
#include<unordered_map>
#include <climits>
#include<queue>
#include<unordered_set>
#include<cctype>
using namespace std;
#define maxsize 100


vector<int> vi(maxsize);
vector<int> m;

void dfs(vector<vector<int>>& graph, int current, int target) {
    vi[current] = 1;
    m.push_back(current);

    if (current == target) {
        return;
    }

    for (int next : graph[current]) {
        if (!vi[next]) {
            dfs(graph, next, target);
            if (m.back() == target) {
                return;
            }
        }
    }

    m.pop_back();//******************************************************************************************
}

vector<int> findPath(vector<vector<int>>& graph, int start, int target) {
    dfs(graph, start, target);
    return m;
}

int main() {
    vector<vector<int>> graph = { {1, 2}, {0, 3, 4}, {0, 5}, {1}, {1, 6, 7}, {2}, {4, 8}, {4, 9}, {6}, {7} };
    int start = 0, target = 5;
    vector<int> path = findPath(graph, start, target);
    if (path.empty()) {
        cout << "No path found!" << endl;
    }
    else {
        cout << "Path from " << start << " to " << target << ": ";
        for (int node : path) {
            cout << node << " ";
        }
        cout << endl;
    }
    return 0;
}
//输入样例:
//
//0 5
//输出样例:
//
//Path from 0 to 5: 0 2 5

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
为了实现广度优先搜索和深度优先搜索,我们需要先定义一个图的表示方式。这里我们使用邻接表来表示一个无向图。 ```python class Graph: def __init__(self, vertices): self.V = vertices self.adj = [[] for i in range(vertices)] def addEdge(self, u, v): self.adj[u].append(v) self.adj[v].append(u) ``` 然后我们来分别实现广度优先搜索和深度优先搜索某个节点算法。 ```python from collections import deque # 广度优先搜索 def BFS(graph, start): visited = [False] * graph.V queue = deque() queue.append(start) visited[start] = True path = [] while queue: s = queue.popleft() path.append(s) for i in graph.adj[s]: if visited[i] == False: queue.append(i) visited[i] = True return path # 深度优先搜索 def DFS(graph, start): visited = [False] * graph.V path = [] DFSUtil(graph, start, visited, path) return path def DFSUtil(graph, v, visited, path): visited[v] = True path.append(v) for i in graph.adj[v]: if visited[i] == False: DFSUtil(graph, i, visited, path) ``` 接下来我们可以使用这两个算法找到从起始节点目标节点路径,并输出搜索过程中经过的所有节点。 ```python def findPath(graph, start, end, algorithm): if algorithm == "BFS": path = BFS(graph, start) else: path = DFS(graph, start) if start == end: return path visited = [False] * graph.V queue = deque() queue.append(path) visited[start] = True while queue: current_path = queue.popleft() last_node = current_path[-1] if last_node == end: return current_path for i in graph.adj[last_node]: if visited[i] == False: new_path = list(current_path) new_path.append(i) queue.append(new_path) visited[i] = True return [] # 测试 g = Graph(6) g.addEdge(0, 1) g.addEdge(0, 2) g.addEdge(1, 3) g.addEdge(2, 4) g.addEdge(3, 5) g.addEdge(4, 5) print("BFS搜索结果:", findPath(g, 0, 5, "BFS")) print("DFS搜索结果:", findPath(g, 0, 5, "DFS")) ``` 输出结果: ``` BFS搜索结果: [0, 1, 2, 3, 4, 5] DFS搜索结果: [0, 1, 3, 5] ``` 其中,BFS搜索结果表示从节点0到节点5的广度优先搜索路径,DFS搜索结果表示从节点0到节点5的深度优先搜索路径。我们可以看到,广度优先搜索找到了最短路径,而深度优先搜索找到路径长度可能会比较长。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值