单选题 适中
#20412

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

给定一个无向图,图的节点编号从 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;
}
未登录也能判分,登录后才会记录
答案与解析
正确答案:D
解析

标记 neighbor 已经入栈并且将 neighbor 入栈,选择 D。(图结构、深度优先搜索)