#4052. [GESP202503 七级 C++] 第 9 题
[GESP202503 七级 C++] 第 9 题
给定一个无向图,图的节点编号从 0 到 n-1,图的边以邻接表的形式给出。下面的程序使用深度优先搜索(DFS)遍历该图,并输出遍历的节点顺序。横线处应该填入的是( )
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
void DFS(int start, vector<vector<int>>& graph, vector<bool>& visited) {
stack<int> s;
s.push(start);
visited[start] = true;
while (!s.empty()) {
int node = s.top();
s.pop();
cout << node << " "; // 输出当前节点
// 遍历邻接节点
for (int neighbor : graph[node]) {
if (!visited[neighbor]) {
__________________
__________________
}
}
}
}
int main() {
int n, m;
cin >> n >> m;
vector<vector<int>> graph(n);
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
graph[u].push_back(v);
graph[v].push_back(u);
}
vector<bool> visited(n, false);
// 从节点 0 开始DFS遍历
DFS(0, graph, visited);
return 0;
}
A.
visited[neighbor] = true;
s.push(neighbor-1);
B.
visited[neighbor] = true;
s.push(neighbor+1);
C.
visited[neighbor] = false;
s.push(neighbor);
D.
visited[neighbor] = true;
s.push(neighbor);
{{ select(1) }}
- A
- B
- C
- D