#include<iostream>
#include<algorithm>
#define MaxVertexNum 2005 //边的最大值
#define MaxSize 505 //顶点数目的最大值
int sort_linklist[MaxSize];
int count_1;
using namespace std;
bool visBFS[MaxSize];
bool visDFS[MaxSize];
bool flag[5010];//记录这个边是否输入过,也算尽量减少空间,不打表了吧(流汗黄豆
typedef int VertexType;
typedef int EdgeType;
typedef struct ArcNode{
EdgeType adjNode;
ArcNode *next;
}ArcNode;//邻接表的边表节点
typedef struct VNode{
VertexType data;
ArcNode *first;
}VNode,AdjList[MaxVertexNum]; //顶点表结点
typedef struct ALGraph{
AdjList vertices;
int vexnum,arcnum;//顶点数弧数
}ALGraph;//图
void CreatGraph(ALGraph &graph){
cin>>graph.vexnum>>graph.arcnum;
for(int i=1;i<=graph.vexnum;i++)//初始化顶点
{
graph.vertices[i].data=i;
graph.vertices[i].first=NULL;
}
int x,y;
for(int i=0;i<graph.arcnum;i++){
cin>>x>>y;
int flag_elem=x*100+y;
if(!flag[flag_elem]) flag[flag_elem]=true;
else{i--;continue;}
ArcNode *p=new ArcNode;
p->adjNode=y;//将y录入边表,比如<1,2>将2录入边表
p->next=graph.vertices[x].first;//将该边表结点的next域指向顶点表结点的first域
graph.vertices[x].first=p;//将顶点表的first域指向p
ArcNode *q=new ArcNode;
q->adjNode=x;//将y录入边表,比如<1,2>将2录入边表
q->next=graph.vertices[y].first;//将该边表结点的next域指向顶点表结点的first域
graph.vertices[y].first=q;//将顶点表的first域指向p
}
for(int i=1;i<=graph.vexnum;i++){
ArcNode *temp=graph.vertices[i].first;
while(temp){
sort_linklist[count_1++]=temp->adjNode;
temp=temp->next;
}
sort(sort_linklist,sort_linklist+count_1);
temp=graph.vertices[i].first;
int j=0;
while(temp){
temp->adjNode=sort_linklist[j++];
temp=temp->next;
}
count_1=0;
}
}
void DestoryGraph(ALGraph &graph){
for(int i=0;i<graph.vexnum;i++){
ArcNode *p=graph.vertices[i].first;
while(p){
ArcNode *q=p;
p=p->next;
delete q;
}
}
}
void DFS_Graph(ALGraph &graph,int v){
count_1++;
visDFS[v]=true;
if(count_1==1) cout<<graph.vertices[v].data;
else cout<<" "<<graph.vertices[v].data;//不好判断结束,从开头入手
ArcNode *p=graph.vertices[v].first;
while(p){
if(!visDFS[p->adjNode]) DFS_Graph(graph,p->adjNode);
p=p->next;
}
}
void BFS_Graph(ALGraph &graph,int v){
visBFS[v]=true;
ArcNode *temp=graph.vertices[v].first;
cout<<graph.vertices[v].data;
if(!temp) cout<<endl;
int queue_self[MaxSize];
int front=0,rear=0;
rear=(rear+1)%MaxSize;
queue_self[rear]=v;
int j;
while(front!=rear){
front=(front+1)%MaxSize;//出队
j=queue_self[front];
temp=graph.vertices[j].first;
while(temp){
if(!visBFS[temp->adjNode]){
visBFS[temp->adjNode]=true;
cout<<" "<<temp->adjNode;
rear=(rear+1)%MaxSize;
queue_self[rear]=temp->adjNode;
}
temp=temp->next;
}
}
}
int main(){
VertexType node;
ALGraph graph;
CreatGraph(graph);
cin>>node;
if(node>=1&&node<=graph.vexnum){
BFS_Graph(graph,node); cout<<endl;
DFS_Graph(graph,node); cout<<endl;
}
else cout<<"起始顶点不存在"<<endl;
DestoryGraph(graph);
return 0;
}
DFSBFS
最新推荐文章于 2024-08-06 17:56:25 发布