邻接矩阵+DFS+BFS
#include<bits/stdc++.h>
using namespace std;
typedef struct
{
char vex[100];
int edge[100][100];
int vexnum,edgenum;
}Graph;
int visitedDFS[100]={0};
int visitedBFS[100]={0};
//构造图
void Create(Graph &g)
{
int vexnum,edgenum;
cin>>vexnum;
char ch;
for(int i=0;i<vexnum;i++)
{
cin>>ch;
g.vex[i]=ch;
}
for(int i=0;i<vexnum;i++)
{
for(int j=0;j<vexnum;j++)
{
g.edge[i][j]=0;
}
}
cin>>edgenum;
int a,b;
for(int k=0;k<edgenum;k++)
{
cin>>a>>b;
g.edge[a][b]=1;
g.edge[b][a]=1;
}
g.vexnum=vexnum;
g.edgenum=edgenum;
}
//深度优先搜索
void DFS(Graph g,int v)//开始节点
{
cout<<g.vex[v]<<" ";
visitedDFS[v]=1;
for(int i=0;i<g.vexnum;i++)
{
if(g.edge[v][i]==1&&visitedDFS[i]==0)
{
DFS(g,i);
}
}
}
void BFS(Graph g,int v)
{
int q[100];
int fro=-1,rear=-1;
cout<<g.vex[v]<<" ";
visitedBFS[v]=1;
rear++;
q[rear]=v;
int w;
while(rear!=fro)
{
fro++;
w=q[fro];
for(int i=0;i<g.vexnum;i++)
{
if(g.edge[w][i]==1&&visitedBFS[i]==0)
{
cout<<g.vex[i]<<" ";
visitedBFS[i]=1;
rear++;
q[rear]=i;
}
}
}
}
int main()
{
Graph g;
Create(g);
DFS(g,0);
cout<<endl;
BFS(g,0);
cout<<endl;
}
邻接表+DFS+BFS
#include<bits/stdc++.h>
using namespace std;
typedef struct EdgeNode
{
int adjvex;
EdgeNode *next;
}EdgeNode;
typedef struct VexNode
{
char vex;
EdgeNode *first;
}VexNode;
typedef struct Graph
{
VexNode adjlist[100];
int vexnum,edgenum;
}Graph;
int visitedDFS[100]={0};
int visitedBFS[100]={0};
void Create(Graph g)
{
int vexnum,edgenum;
cin>>vexnum;
char ch;
for(int i=0;i<vexnum;i++)
{
cin>>ch;
g.adjlist[i].vex=ch;
g.adjlist[i].first=NULL;
}
cin>>edgenum;
EdgeNode *en=NULL;
int a,b;
for(int k=0;k<edgenum;k++)
{
cin>>a>>b;
en=(EdgeNode*)malloc(sizeof(EdgeNode));
en->adjvex=b;
en->next=g.adjlist[a].first;
g.adjlist[a].first=en;
}
g.vexnum=vexnum;
g.edgenum=edgenum;
}
//DFS
void DFS(Graph g,int v)
{
EdgeNode *p=NULL;
cout<<g.adjlist[v].vex<<" ";
visitedDFS[v]=1;
p=g.adjlist[v].first;
int k;
while(p!=NULL)
{
k=p->adjvex;
if(visitedDFS[k]==0)
{
DFS(g,k);
}
p=p->next;
}
}
void BFS(Graph g,int v)
{
int w;
int q[100];
int rear=-1,fro=-1;
EdgeNode *p=NULL;
cout<<g.adjlist[v].vex<<" ";
visitedBFS[v]=1;
rear++;
q[rear]=v;
int k;
while(rear!=fro)
{
fro++;
w=q[fro];
p=g.adjlist[w].first;
while(p!=NULL)
{
k=p->adjvex;
if(visitedBFS[k]==0)
{
cout<<g.adjlist[k].vex<<" ";
visitedBFS[k]=1;
rear++;
q[rear]=k;
}
p=p->next;
}
}
}
int main()
{
Graph g;
Create(g);
cout<<g.adjlist[0].vex<<endl;
DFS(g,0);
cout<<endl;
BFS(g,0);
cout<<endl;
}
Prim+Kruskal+Dijkstra+Floyd
以前的我好牛逼。。。