测评会员优惠活动进行中 · 开通 VIP,有效期内测评不限次 VIP 优惠中 · 测评不限次 立即查看

A28354. 给定一个无向图,图的节点编号从 0 到 n-1,图的边以邻接表的形式给出。下面的程序使用深度优先搜索(DFS)遍历该图,并输出遍历的节点顺序。横线处应该填入的是( )#include <iostream> #include <vector> #include <stack> using namespace std; void DFS(int start, vector<vector<int>>&…

单选题 困难

题目描述

给定一个无向图,图的节点编号从 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;
}

选项(单选)

上一题 下一题