【C++】基于邻接矩阵的图的深度优先遍历(DFS)和广度优先遍历(BFS)

时间:2023-03-09 01:28:06
【C++】基于邻接矩阵的图的深度优先遍历(DFS)和广度优先遍历(BFS)

写在前面:本博客为本人原创,严禁任何形式的转载!本博客只允许放在博客园(.cnblogs.com),如果您在其他网站看到这篇博文,请通过下面这个唯一的合法链接转到原文!

本博客全网唯一合法URL:https://www.cnblogs.com/acm-icpcer/p/10458956.html

算法思想使用的是殷人昆《数据结构(基于面向对象和C++)》第二版P364页的程序8.9&P366程序8.10

#include<iostream>
#include<cstdlib>
#include<cstring>
using namespace std;
const long M=; struct node
{
int data;
struct node* next;
}; class Q
{
private:
node *head,*rear;
public:
Q()//this actually ruled that we do not use first node
{
head=new node();
rear=head;
}
void add(int a)
{
node *t=new node();
t->data=a;
rear->next=t;
rear=rear->next;
}
int remove()
{
node *t=head->next;
int result=t->data;
head->next=t->next;
delete t;
return result;
} node* gethead()
{
return head;
} bool isempty()
{
if(head->next==NULL)
return true;
else return false;
}
}; class G
{
private:
int map[M][M];
int visited[M];
int m;
public:
G()
{
cin>>m;
reset();
clean();
build();
} void reset()
{
memset(map,,sizeof(map));
cout<<"reset over!"<<endl;
} void clean()
{
memset(visited,,sizeof(visited));
cout<<"clean over!"<<endl;
} void build()
{
for(int i=;i<m;i++)
for(int j=;j<m;j++)
scanf("%d",&map[i][j]);
} void display()
{
cout<<"displaying:"<<endl;
for(int i=;i<m;i++)
{
for(int j=;j<m;j++)
cout<<map[i][j];
cout<<endl;
}
} int getfirstedge(int v)
{
if(v>m||v<) return -;
int i=;
while(map[v][i]<=&&i<m) i++;
if(i>m||i<) return -;
return i;
} int getnextedge(int v,int w)
{
int i=w+;
if(v>m||v<||i>m||i<) return -;
while(map[v][i]<=&&i<m) i++;
if(i>m||i<) return -;
return i;
}
/*
void dfs(int i,int j)
{
if(i>m||j>m||i<0||j<0||visited[i][j])
return; ++visited[i][j]; if(map[i][j]>0)
cout<<"node->"<<i<<":"<<map[i][j]; dfs(i-1,j);
dfs(i,j-1);
dfs(i+1,j);
dfs(i,j+1);
}
*/ void dfs(int v)//v represents a node
{
cout<<v;
visited[v]=;
int w=this->getfirstedge(v);
while(w>=&&w<m)
{
if(visited[w]!=)
dfs(w);
w=this->getnextedge(v,w);
}
} void bfs(int v)
{
Q *q=new Q();
cout<<v;
visited[v]=;
q->add(v);
while(!q->isempty())
{
int loc=q->remove();
int w=this->getfirstedge(loc);
while(w>=&&w<m)
{
if(visited[w]==false)
{
cout<<w;
visited[w]=;
q->add(w);
}
w=this->getnextedge(loc,w);
}
} } }; int main()
{
G *obj1=new G();
obj1->display();
/*
cout<<obj1->getfirstedge(1)<<endl;
cout<<obj1->getnextedge(1,obj1->getfirstedge(1))<<endl;
*/
obj1->clean();
cout<<"dfs:"<<endl;
obj1->dfs();
cout<<endl; obj1->clean();
cout<<"bfs:"<<endl;
obj1->bfs();
cout<<endl; return ;
}

代码运行说明:

【C++】基于邻接矩阵的图的深度优先遍历(DFS)和广度优先遍历(BFS)

tz@HZAU

2019/3/2