void bfs1(int start, int target) { queue<int> q; q.push(start); bool visited[MAXN] = { false }; visited[start] = true; int parent[MAXN] = { -1 }; while (!q.empty()) { int current = q.front(); q.pop(); if (current == target) { cout << "找到目标节点的值为: " << target << endl; cout << "路径为: "; vector<int> path; int p = target; while (p != -1) { path.push_back(p); p = parent[p]; } for (int i = path.size() - 1; i >= 0; i--) { cout << nodes[path[i]] << " "; } cout << endl; return; } cout << "搜索经过的节点: " << nodes[current] << endl; for (int neighbor : adjacencyList[current]) { if (!visited[neighbor]) { q.push(neighbor); visited[neighbor] = true; parent[neighbor] = current; } } } cout << "找不到目标节点。 " << nodes[target] << endl; }将代码改为实现深度优先搜索某个节点,并输出该节点的值,同时输出搜索过程经过的节点。路径显示过程以节点A为起始节点,目标节点为终点。
时间: 2023-06-25 09:06:28 浏览: 32
void dfs(int current, int target, bool visited[], int parent[]) {
visited[current] = true;
cout << "搜索经过的节点: " << nodes[current] << endl;
if (current == target) {
cout << "找到目标节点的值为: " << nodes[target] << endl;
cout << "路径为: ";
vector<int> path;
int p = target;
while (p != -1) {
path.push_back(p);
p = parent[p];
}
for (int i = path.size() - 1; i >= 0; i--) {
cout << nodes[path[i]] << " ";
}
cout << endl;
return;
}
for (int neighbor : adjacencyList[current]) {
if (!visited[neighbor]) {
parent[neighbor] = current;
dfs(neighbor, target, visited, parent);
}
}
}
void dfs1(int start, int target) {
bool visited[MAXN] = { false };
int parent[MAXN] = { -1 };
dfs(start, target, visited, parent);
if (!visited[target]) {
cout << "找不到目标节点。 " << nodes[target] << endl;
}
}
// 调用方式
dfs1(start, target);
// 其中start为起始节点的索引,target为目标节点的索引。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)