登 录
#include<stdio.h> #include<stdlib.h> #define VV 100 #define EE 999 #include<iostream> using namespace std; bool visited[100]; int q[100]; struct graph{ int v,e; char vex[VV]; int edge[EE][EE]; }; //构造图 void createGraph(graph * g){ int i=0,j=0; printf("type the number of vertex:/n"); scanf("%d",&g->v); printf("type the number of edge:/n"); scanf("%d",&g->e); printf("type the vertex:/n"); cout<<"gg"<<g->v<<endl; for(i=0;i<g->v;i++){cin>>g->vex[i];} printf("type the edge:/n"); for(i=0;i<g->v;i++){ for(j=0;j<g->v;j++){cin>>g->edge[i][j];} } } //深度搜索 void dfs(graph * g,int v){ int i; cout<<g->vex[v]<<endl; visited[v]=1; for(i=0;i<g->v;i++){ if(visited[i]!=1&&g->edge[v][i]!=0) dfs(g,i); } } //广度搜索 void bfs(graph * g, int v){ int i; int front,rear; front=rear=-1; cout<<g->vex[v]<<endl; visited[v]=1; q[++rear]=v; while(front!=rear){ v=q[++front]; for(i=0;i<g->v;i++){ if(visited[i]!=1&&g->edge[v][i]!=0){ cout<<g->vex[i]<<endl; visited[i]=1; q[++rear]=i; } } } } int main() { graph * g; g=(graph *)malloc(sizeof(graph)); createGraph(g); dfs(g,0); memset(visited,0,sizeof(visited)); bfs(g,0); return 0; }
抱歉!评论已关闭.