第一个DFS
#include <iostream>
#include <vector>
using namespace std;
void DFS(int v, vector<bool>& visited, const vector<vector<int>>& graph) {
visited[v] = true;
cout << v << " ";
for (int neighbor : graph[v]) {
if (!visited[neighbor]) {
DFS(neighbor, visited, graph);
}
}
}
int main() {
vector<vector<int>> graph = {
{1, 2}, // 0
{0, 3, 4}, // 1
{0, 4}, // 2
{1}, // 3
{1, 2} // 4
};
vector<bool> visited(graph.size(), false);
cout << "Depth First Search starting from vertex 0:\n";
DFS(0, visited, graph);
return 0;
}
第二个BFS
#include <iostream>
#include <vector>
#include <queue>
void BFS(int start, const std::vector<std::vector<int>>& graph) {
std::vector<bool> visited(graph.size(), false);
std::queue<int> queue;
visited[start] = true;
queue.push(start);
while (!queue.empty()) {
int v = queue.front();
queue.pop();
std::cout << v << " ";
for (int neighbor : graph[v]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.push(neighbor);
}
}
}
}
int main() {
std::vector<std::vector<int>> graph = {
{1, 2}, // 0
{0, 3, 4}, // 1
{0, 4}, // 2
{1}, // 3
{1, 2} // 4
};
std::cout << "Breadth First Search starting from vertex 0:\n";
BFS(0, graph);
return 0;
}
(想要原代码+注释)