1 深度优先遍历邻接矩阵
1 邻接矩阵初始化
2 访问数组初始化
3 深度优先遍历邻接矩阵图
算法如下:
bool MGraph[128][128]; bool visit[128]; int vexnum; //num of vertices void dfs(int u){ visit[u] = true; for(int v = 0; v < vexnum ; v++ ){ if( !visit[v] && MGraph[u][v]) dfs(v); }
source code:
#include <iostream> #include <stdlib.h> using namespace std; #define MAX_VERTEX_NUM 128 bool MGraph[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; bool visit[MAX_VERTEX_NUM]; int vexnum; void dfs(int u){ visit[u] = true; //for print cout<<u + 1<<" "; for(int v = 0; v < vexnum ; v++ ){ if( !visit[v] && MGraph[u][v]){ dfs(v); } } } int main(){ //initialize M Graph int i, j, edge_num; cout<<"enter vertex number and edge number:"<<endl; cin>>vexnum>>edge_num; //initialize edge of graph while(edge_num){ cout<<"enter edge:"<<endl; cin>>i>>j; MGraph[i-1][j-1] = true; MGraph[j-1][i-1] = true; edge_num--; } for(i = 0; i < vexnum; i++) visit[i] = false; for(i = 0; i < vexnum ; i++){ if(!visit[i]) dfs(i); } system("pause"); return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。