#include <iostream> #include <queue> using namespace std; const int SIZE = 5; // 深度优先遍历 void depthFirstTraversal(bool graph[SIZE][SIZE], bool visited[SIZE], int vertex) { cout << vertex << " "; visited[vertex] = true; for (int i = 0; i < SIZE; i++) { if (graph[vertex][i] && !visited[i]) { depthFirstTraversal(graph, visited, i); } } } // 广度优先遍历 void breadthFirstTraversal(bool graph[SIZE][SIZE], bool visited[SIZE], int startVertex) { queue<int> q; visited[startVertex] = true; q.push(startVertex); while (!q.empty()) { int vertex = q.front(); q.pop(); cout << vertex << " "; for (int i = 0; i < SIZE; i++) { if (graph[vertex][i] && !visited[i]) { visited[i] = true; q.push(i); } } } } int main() { bool graph[SIZE][SIZE] = { {0, 1, 0, 1, 0}, {1, 0, 1, 0, 0}, {0, 1, 0, 1, 1}, {1, 0, 1, 0, 1}, {0, 0, 1, 1, 0} }; bool visited[SIZE] = { false }; cout << "Depth First Traversal: "; depthFirstTraversal(graph, visited, 0); cout << endl; // Reset visited array for (int i = 0; i < SIZE; i++) { visited[i] = false; } cout << "Breadth First Traversal: "; breadthFirstTraversal(graph, visited, 0); cout << endl; return 0; } 给这段代码加上注释
时间: 2024-01-26 11:04:34 浏览: 110
#include <iostream> #include<iomanip> using namespace std;九九乘法表
```
#include <iostream>
#include <queue>
using namespace std;
const int SIZE = 5; // 图的大小
// 深度优先遍历
void depthFirstTraversal(bool graph[SIZE][SIZE], bool visited[SIZE], int vertex) {
cout << vertex << " "; // 输出访问的节点号
visited[vertex] = true; // 标记该节点已被访问
// 遍历所有与该节点相邻的节点
for (int i = 0; i < SIZE; i++) {
if (graph[vertex][i] && !visited[i]) { // 如果该节点与i节点相邻,并且i节点未被访问
depthFirstTraversal(graph, visited, i); // 递归访问i节点
}
}
}
// 广度优先遍历
void breadthFirstTraversal(bool graph[SIZE][SIZE], bool visited[SIZE], int startVertex) {
queue<int> q; // 声明一个队列
visited[startVertex] = true; // 标记起始节点已被访问
q.push(startVertex); // 将起始节点入队
while (!q.empty()) { // 处理队列中的所有节点
int vertex = q.front(); // 取出队列头部节点
q.pop(); // 移除队列头部节点
cout << vertex << " "; // 输出访问的节点号
// 遍历所有与该节点相邻的节点
for (int i = 0; i < SIZE; i++) {
if (graph[vertex][i] && !visited[i]) { // 如果该节点与i节点相邻,并且i节点未被访问
visited[i] = true; // 标记i节点已被访问
q.push(i); // 将i节点入队
}
}
}
}
int main() {
bool graph[SIZE][SIZE] = {
{0, 1, 0, 1, 0},
{1, 0, 1, 0, 0},
{0, 1, 0, 1, 1},
{1, 0, 1, 0, 1},
{0, 0, 1, 1, 0}
};
bool visited[SIZE] = { false }; // 初始化节点访问状态为未访问
cout << "Depth First Traversal: ";
depthFirstTraversal(graph, visited, 0); // 从0号节点开始深度优先遍历
cout << endl;
// 重置节点访问状态为未访问
for (int i = 0; i < SIZE; i++) {
visited[i] = false;
}
cout << "Breadth First Traversal: ";
breadthFirstTraversal(graph, visited, 0); // 从0号节点开始广度优先遍历
cout << endl;
return 0;
}
```
阅读全文