今天写的内容是在CSDN看到一些有关于优先搜索讲解的文章,然后有一些理解。
广度优先搜索和深度优先搜索就是图的遍历,那什么叫做图的遍历呢,从图的某个顶点出发,沿图中的路径依次访问图中所有顶点,并且使得图中所有顶点都恰好被访问一次,这一过程即为图的遍历。需要注意的是,接下来讨论图的遍历时,都是特指在一个连通图上进行遍历。
图有最两种常见的遍历方法,就是广度优先搜索和深度优先搜索。
简单来说广度优先搜索就是一层一层地往下走,而深度优先搜索则是照着一条路径一个劲儿的往下走(就像是不撞南墙不回头)。
而在解决最短路径的问题时,像迷宫这种类型的问题时,就可以很好的利用BFS来解决。
迷宫问题原题目
https://blog.csdn.net/C20190413/article/details/73103529
这代题目的代码就充分体现了广度优先搜索的内容。
代码
#include<cstdio>
#include<cstring>
int head=0,tail=1,nextx,nexty;
int pre[100000],a[100000],b[100000];
int x[4]={0,0,1,-1},y[4]={1,-1,0,0};
bool mark[5][5];
int map[5][5];
int wayx[25],wayy[25];
void find(int d)
{
if(pre[d]!=0){find(pre[d]);printf("(%d, %d)\n",wayx[d],wayy[d]);}
}
bool check(int x,int y)
{
if(x<5&&y<5&&x>=0&&y>=0)return 1;
return 0;
}
void bfs()
{
a[1]=0;
b[1]=0;
mark[0][0]=1;
pre[1]=0;
head=0;tail=1;
while(head!=tail)
{
head++;
for(int i=0;i<4;i++)
{
nextx=a[head]+x[i];
nexty=b[head]+y[i];
if(check(nextx,nexty)&&!mark[nextx][nexty]&&map[nextx][nexty]==0)
{
tail++;
a[tail]=nextx;
b[tail]=nexty;
pre[tail]=head;
wayx[tail]=nextx;
wayy[tail]=nexty;
mark[nextx][nexty]=1;
if(a[tail]==4&&b[tail]==4)
{
printf("(0, 0)\n");
find(tail);
return ;
}
}
}
}
}
main()
{
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
scanf("%d",&map[i][j]);
bfs();
}