第21259题 单选题
给定基于栈实现DFS遍历无向图的C++程序,横线处应填入哪组代码

给定一个无向图,图的节点编号从0到n-1,图的边以邻接表的形式给出。下面的程序使用深度优先搜索(DFS)遍历该图,并输出遍历的节点顺序。横线处应该填入的是:

1 #include <iostream> 
2 #include <vector> 
3 #include <stack> 
4 using namespace std; 

6 void DFS(int start, vector<vector<int>>& graph, vector<bool>& visited) { 
7  stack<int> s; 
8  s.push(start); 
9  visited[start] = true; 

11  while (!s.empty()) { 
12   int node = s.top(); 
13   s.pop(); 
14   cout << node << " "; // 输出当前节点 

15   // 遍历邻接节点 
17   for (int neighbor : graph[node]) { 
18    if (!visited[neighbor]) { 
19     __________________ 
20     __________________ 

21    } 
22   } 
23  }
24 } 

27 int main() { 
28  int n, m; 
29  cin >> n >> m; 

31  vector<vector<int>> graph(n); 
32  for (int i = 0; i < m; i++) { 
33   int u, v; 
34   cin >> u >> v; 
35   graph[u].push_back(v); 
36   graph[v].push_back(u); 
37  } 

40  vector<bool> visited(n, false); 

42  // 从节点 0 开始DFS遍历 
43  DFS(0, graph, visited); 

45  return 0; 
46 }
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);
程序运行统计
暂无判题统计