用markdown格式写一篇图的应用的C++博客附代码
图的应用:C++实现图的遍历
图是一种非线性的数据结构,由一组节点和节点之间的边组成。图的应用非常广泛,比如社交网络、地图导航和搜索引擎等。在本篇博客中,我们将使用C++编程语言来实现图的遍历算法。
图的表示
图可以用邻接矩阵或邻接表来表示。在本篇博客中,我们选择使用邻接矩阵来表示图。邻接矩阵是一个二维数组,其中的元素表示节点之间的连接关系。如果节点i和节点j之间存在边,则邻接矩阵的第i行第j列和第j行第i列的元素值为1,否则为0。
const int MAX_SIZE = 100;
class Graph {
private:
int matrix[MAX_SIZE][MAX_SIZE];
int numVertices;
public:
Graph(int vertices) {
numVertices = vertices;
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
matrix[i][j] = 0;
}
}
}
void addEdge(int start, int end) {
matrix[start][end] = 1;
matrix[end][start] = 1;
}
void printGraph() {
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
}
};
图的遍历
图的遍历是指按照一定的顺序访问图中的所有节点。常见的图的遍历算法有深度优先搜索(DFS)和广度优先搜索(BFS)。
深度优先搜索
深度优先搜索从起始节点开始,沿着一条路径一直访问到最后一个节点,然后回溯到上一个节点,再继续访问它的下一个节点,直到遍历完所有的节点。
class GraphTraversal {
private:
bool visited[MAX_SIZE];
public:
void DFS(Graph& graph, int start) {
visited[start] = true;
cout << start << " ";
for (int i = 0; i < graph.getNumVertices(); i++) {
if (graph.getMatrix()[start][i] == 1 && !visited[i]) {
DFS(graph, i);
}
}
}
};
广度优先搜索
广度优先搜索从起始节点开始,先访问起始节点的所有邻居节点,然后再按顺序访问邻居节点的邻居节点,直到遍历完所有的节点。
class GraphTraversal {
private:
bool visited[MAX_SIZE];
public:
void BFS(Graph& graph, int start) {
queue<int> q;
visited[start] = true;
q.push(start);
while (!q.empty()) {
int current = q.front();
q.pop();
cout << current << " ";
for (int i = 0; i < graph.getNumVertices(); i++) {
if (graph.getMatrix()[current][i] == 1 && !visited[i]) {
visited[i] = true;
q.push(i);
}
}
}
}
};
测试
我们可以使用以下代码来测试图的遍历算法:
int main() {
Graph graph(6);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(1, 4);
graph.addEdge(2, 4);
graph.addEdge(3, 4);
graph.addEdge(3, 5);
graph.addEdge(4, 5);
cout << "Graph:" << endl;
graph.printGraph();
cout << "DFS traversal: ";
GraphTraversal traversal;
traversal.DFS(graph, 0);
cout << endl;
cout << "BFS traversal: ";
traversal.BFS(graph, 0);
cout << endl;
return 0;
}
输出结果为:
Graph:
0 1 1 0 0 0
1 0 0 1 1 0
1 0 0 0 1 0
0 1 0 0 1 1
0 1 1 1 0 1
0 0 0 1 1 0
DFS traversal: 0 1 3 4 2 5
BFS traversal: 0 1 2 3 4 5
以上就是使用C++实现图的遍历算法的示例。图的遍历是图算法中的基础,理解了图的遍历算法,就可以在此基础上实现更复杂的图算法。希望本篇博客对您理解图的应用有所帮助
原文地址: https://www.cveoy.top/t/topic/h96n 著作权归作者所有。请勿转载和采集!