dfs
#include <malloc.h> #include <iostream> using namespace std; #define INFINITY 32767 #define MAX_VEX 50 //最大顶点个数 #define OK 1 #define FALSE 0 #define TRUE 1 #define ERROR -1 bool *visited; //动态分配访问标志数组 //图的邻接矩阵存储结构 typedef struct { char *vexs; //动态分配空间存储顶点向量 int arcs[MAX_VEX][MAX_VEX]; //邻接矩阵 int vexnum, arcnum; //图的当前定点数和弧数 }Graph; //图G中查找顶点c的位置 int LocateVex(Graph G, char c) { for(int i = 0; i < G.vexnum; ++i) { if(G.vexs[i] == c) return i; } return ERROR; } //创建无向网 void CreateUDN(Graph &G){ //采用数组(邻接矩阵)表示法,构造无向网G cout << "请输入定点数和弧数:"; cin >> G.vexnum >> G.arcnum; cout << "请输入" << G.vexnum << "个顶点" << endl; G.vexs = (char *) malloc((G.vexnum+1) * sizeof(char)); //需要开辟多一个空间存储'\0' //构造顶点向量 for(int i = 0; i < G.vexnum; i++) { cout << "请输入第" << i+1 << "个顶点:"; cin >> G.vexs[i]; } G.vexs[G.vexnum] = '\0'; //初始化邻接矩阵 for(i = 0; i < G.vexnum; ++i) for( int j = 0; j < G.vexnum; j++) G.arcs[i][j] = INFINITY; cout << "请输入" << G.arcnum << "条弧" << endl; char a, b; int s1, s2; for(i = 0; i < G.arcnum; ++i) { cout << "请输入第" << i+1 << "条弧:"; cin >> a >> b ; //输入依附于弧的权值 s1 = LocateVex(G,a); //找到a和b在顶点向量中的位置 s2 = LocateVex(G,b); G.arcs[s1][s2] = G.arcs[s2][s1] = 1; //权值默认为1 } } //图G中顶点k的第一个邻接顶点 int FirstVex(Graph G,int k){ for(int i = 0; i < G.vexnum; ++i) if (G.arcs[k][i] != INFINITY) return i; return ERROR; } //返回i(相对于j)的下一个邻接顶点 int NextVex(Graph G,int i,int j){ for(int k = j+1; k < G.vexnum; ++k) if(G.arcs[i][k] != INFINITY) return k; return ERROR; } void DFS(Graph G, int v) { //从第v个顶点出发递归地深度优先遍历图G visited[v] = TRUE; cout << G.vexs[v] << " "; for(int w = FirstVex(G,v); w >= 0; w = NextVex(G,v,w)) if(!visited[w]) DFS(G,w); } //深度优先遍历 void DFSTraverse(Graph G, int i) { for(int j = 0; j < G.vexnum; ++j) { //初始化所有的顶点状态为未被访问 visited[j] = FALSE; } //遍历结点 for(; i < G.vexnum; ++i) if(!visited[i]) DFS(G,i); } //主函数 void main(){ Graph G; CreateUDN(G); visited = (bool *) malloc(G.vexnum * sizeof(bool)); cout << endl << "深度优先遍历:"; DFSTraverse(G,0); cout << endl; }