《啊哈!算法》之图的遍历——深度广度优先算法
- 什么是图
- 深度优先遍历
- 广度优先遍历
什么是图
简单地说,图就是由一些小圆点(称为顶点)和连接这些小圆点的直线(称为边)组成的
这些箭头代表着只能单向访问,比如只能A→B,不能B→A,为有向图,反之为无向图
数字代表着访问顺序
了解了什么是图过后那么我们怎么用程序把图表示出来
最常用的方法是用一个二维数组e来存储,如下:
上图二维数组中第i行第j列表示的就是顶点i到顶点j是否有边。1表示有边,∞表示没有边,这里我们将自己到自己(即 i=j)设为0。我们将这种存储图的方法称为图的邻接矩阵存储法。
深度优先遍历
深度优先遍历的主要思想就是:首先以一个未被访问过的顶点作为起始顶点,沿当前项点的边走到未访问过的顶点;当没有未访
问过的顶点时,则回到上一个顶点,继续试探访问别的顶点,直到所有的顶点都被访问过。
举一个例子:城市地图——寻找最短路程
需要输入城市的数量(顶点),公路的数量(边)。每条公路需要类似”a,b,c“这样的数据,表示有一条路可以从城市a到城市b,并且路程为c公里,这里的公路都是单行的。现在求出出发地到目的地的最短路程。
#include<iostream>
using namespace std;
int minute=99999;
int n,p,m=0;
int e[101][101],book[101]; //建立地图与标记数组
#define MAX 9999
void dfs(int cur,int dis) //深度优先搜索的核心代码
{
int i;
if(cur == p)
{
if(minute > dis)
minute=dis;
return ; //回溯
}
for(i=1;i<=p;++i)
{
if((e[cur][i] != MAX) && (book[i] == 0))
{
book[i]=1;
dfs(i,dis+e[cur][i]);
book[i]=0;
}
}
return ;
}
int main()
{
int a,b,c,i,j;
cout << "please input the number of the city: ";
cin >> n;
cout << "please input your destination: ";
cin >>p;
cout << "please input the number of the roads: ";
cin >> m;
for(i=1;i<=n;++i) //通过一个二维数组存储该图
{
for(j=1;j<=n;++j)
{
if(i == j)
e[i][j]=0;
else
e[i][j]=MAX;
}
}
for(int k=1;k<=m;++k)
{
cin >> a >> b >> c;
e[a][b]=c;
}
dfs(1,0);
cout << "the minute: " << minute << " km ." <<endl;
return 0;
}
广度优先遍历
广度优先遍历的主要思想是:首先以一个未被访问过的顶点作为起始顶点,访问其所有相邻的顶点,然后对每个相邻的顶点,再访
问它们相邻的未被访问过的顶点,直到所有项点都被访问过,遍历结束。
举个列子:乘机旅游——最少转机
需要输入城市的数量(顶点),航线的数量(边)。每条航线需要类似”a,b“这样的数据,表示有一条路可以从城市a到城市b,这里的航线都是双向的。现在求出出发地到目的地的最少转机次数。
#include<iostream>
using namespace std;
#define MAX 9999
int e[101][101],book[101]; //建立地图与标记数组
int n,m,p,s;
int head,tail;
struct note //建立队列
{
int x; //存储顶点
int s; //存储转机次数
};
int main()
{
int a,b,i,j,flag=0;
struct note que[100];
head=tail=1;
cout << "please input the number of the city: ";
cin >> n;
cout << "please input your departure: ";
cin >> s;
cout << "please input your destination: ";
cin >>p;
cout << "please input the number of the roads: ";
cin >> m;
for(i=1;i<=n;++i) //通过一个二维数组存储该图
{
for(j=1;j<=n;++j)
{
if(i == j)
e[i][j]=0;
else
e[i][j]=MAX;
}
}
for(int k=1;k<=m;++k)
{
cin >> a >> b;
e[a][b]=1;
e[b][a]=1; //注意为无向图
}
que[tail].x=s;
que[tail].s=0;
++tail;
while(head < tail) //广度优先遍历核心代码
{
int cur;
cur=que[head].x;
for(i=1;i<=n;++i)
{
if((e[cur][i] != MAX) && (book[i] == 0))
{
que[tail].x=i;
que[tail].s=que[head].s++;
++tail;
book[i]=1;
}
if(que[tail-1].x == p)
{
flag=1;
break;
}
}
if(flag == 1)
break;
++head; //当一个点扩展结束后,head++才能继续扩展
}
cout << "turn " << que[tail-1].s << " times .";
return 0;
}