#include<iostream>#include<queue>usingnamespace std;int graph[30][30]={0};int ind[30]={0};bool vis1[30],vis2[30];voiddfs(int v){printf(" %c", v +'A');
vis1[v]=true;for(int i =0; i <26; i++)if(graph[v][i]&&!vis1[i])dfs(i);}voidbfs(int v){
queue<int>q;
q.push(v);
vis2[v]=true;int u;while(!q.empty()){
u = q.front();
q.pop();for(int i=0;i<26;i++)if(graph[u][i]&&!vis2[i]){
vis2[i]=true;
q.push(i);}printf(" %c", u +'A');}}intmain(){char u, v;int w, n, m;
cin >> n >> m;for(int i =0; i < m; i++){getchar();scanf("%c %c %d",&u,&v,&w);
graph[u -'A'][v -'A']= graph[v -'A'][u -'A']= w;
ind[u -'A']++;
ind[v -'A']++;}printf("DFS:");for(int i =0; i <26; i++)if(ind[i]&&!vis1[i])dfs(i);putchar('\n');printf("BFS:");for(int i =0; i <26; i++)if(ind[i]&&!vis2[i])bfs(i);putchar('\n');for(int i =0; i <26; i++){if(ind[i])printf("%c:%d\n", i +'A',ind[i]);}return0;}
邻接表存图与深搜广搜遍历图
#include<iostream>#include<queue>#include<vector>usingnamespace std;structedge{int to, w;edge(int a,int b):to(a),w(b){}};
vector<edge>graph[30];int ind[30]={0};bool vis1[30],vis2[30];voiddfs(int v){printf(" %c", v +'A');
vis1[v]=true;for(int i =0; i < graph[v].size(); i++)if(!vis1[graph[v][i].to])dfs(graph[v][i].to);}voidbfs(int v){
queue<int>q;
q.push(v);
vis2[v]=true;int u;while(!q.empty()){
u = q.front();
q.pop();for(int i =0; i < graph[u].size(); i++)if(!vis2[graph[u][i].to]){
vis2[graph[u][i].to]=true;
q.push(graph[u][i].to);}printf(" %c", u +'A');}}intmain(){char u, v;int w, n, m;
cin >> n >> m;for(int i =0; i < m; i++){getchar();scanf("%c %c %d",&u,&v,&w);
graph[v -'A'].push_back({ u -'A',w });
graph[u -'A'].push_back({ v -'A',w });
ind[u -'A']++;
ind[v -'A']++;}printf("DFS:");for(int i =0; i <26; i++)if(ind[i]&&!vis1[i])dfs(i);putchar('\n');printf("BFS:");for(int i =0; i <26; i++)if(ind[i]&&!vis2[i])bfs(i);putchar('\n');for(int i =0; i <26; i++){if(ind[i])printf("%c:%d\n", i +'A', ind[i]);}return0;}