图的遍历——DFS(邻接矩阵)
递归 + 标记
一个连通图只要DFS一次,即可打印所有的点。
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <malloc.h> using namespace std; const int VERTEX_NUM = 20; const int INFINITY = 0x7fffffff; // 最大int型数,表示权的无限值 bool vis[VERTEX_NUM]; class Graph { public: int vexNum; int edgeNum; int vex[VERTEX_NUM]; int arc[VERTEX_NUM][VERTEX_NUM]; }; void createGraph(Graph &G) { cout << "please input vexNum and edgeNum: "; cin >> G.vexNum >> G.edgeNum; for (int i = 0; i != G.vexNum; ++i) { cout << "please input no" << i+1 << " vertex: "; cin >> G.vex[i]; } for (int i = 0; i != G.vexNum; ++i) { for (int j = 0; j != G.vexNum; ++j) { G.arc[i][j] = INFINITY; } } for (int k = 0; k != G.edgeNum; ++k) { cout << "please input the vertex of edge(vi, vj) and weight: "; int i, j, w; cin >> i >> j >> w; G.arc[i][j] = w; G.arc[j][i] = G.arc[i][j]; // 无向图 } } void DFS(const Graph &G, int k) { vis[k] = true; cout << G.vex[k] << " "; // 打印图的结点 for (int i = 0; i != G.vexNum; ++i) { if (G.arc[k][i] != INFINITY && !vis[i]) DFS(G, i); } } void DFSTraverse(const Graph &G) { memset(vis, false, VERTEX_NUM); // 连通图一次即遍历完成 for (int i = 0; i != G.vexNum; ++i) { if (!vis[i]) DFS(G, i); } } int main() { Graph G; createGraph(G); DFSTraverse(G); return 0; }