一、算法概述
BFS算法本质就是从起点到终点找到最近的距离。
BFS算法核心把一个问题抽象成图,从一个点开始,向四周开始扩散。
比DFS的空间复杂度大。
二、算法框架
int BFS(Node start, Node target)
{
Queue<Node> q; //核心数据结构
Set<Node> visited;
int step = 0;
q.push(start); //从当前点开始
visited.insert(start);
while(!q.empty*())
{
int sz = q.size();
{
node cur = q.front();
q.pop();
if( cur is target) //排队呢是否达到target
return step;
for(int cur_temp=cur.adj()) //adj()函数是指cur上下左右的值
{
if(cur_temp not in visited)
{
q.push(cur_temp );
visited.insert(cur_temp )
}
}
}
//划重点: 更新步数在这⾥
step++;/
}
}
三、C++走迷宫BFS算法案例
#include <iostream>
#include <cstdio>
#include <queue>
#include <set>
#include<algorithm>
/*
这里有一个5 * 5的迷宫,1是墙,0是路,那么从左上角走道右下角最少需要多少步呢?
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
首先把终点设为3,走过的路设为2,
*/
using namespace std;
int Map[5][5] = {0,1,0,0,0 ,0,1,0,1,0, 0,0,0,0,0 ,0,1,1,1,0 ,0,0,0,1,0}; //定义地图大小
int dir[4][2] = { 1,0,-1,0,0,-1,0,1 }; //定义方向
int n, m, ans;
struct node
{
int x, y;
//node() {}
node(int _x, int _y)
{
this->x=_x;
this->y=_y;
}
bool operator<(const struct node & right)const //重载<运算符
{
if(this->x == right.x && this->y == right.y ) //根据x,y去重
return false;
else
{
if(this->x != right.x)
{
return this->x > right.x; //降序
}
else
{
return this->y > right.y;
}
}
}
}; //保存走步
node plusOne(struct node cur, int i)
{
node cur_temp(0,0);
if (i == 0)
{
cur_temp.x = cur.x + 1;
cur_temp.y = cur.y;
}
if (i == 1)
{
cur_temp.x = cur.x - 1;
cur_temp.y = cur.y;
}
if (i == 2)
{
cur_temp.x = cur.x;
cur_temp.y = cur.y +1;
}
if (i == 3)
{
cur_temp.x = cur.x;
cur_temp.y = cur.y - 1;
}
if (cur_temp.x < 0 || cur_temp.y < 0 || cur_temp.x >=5 || cur_temp.y >=5)
{
cur_temp.x = -1;
cur_temp.y =-1;
}
return cur_temp;
}
set <node> visited;
queue<node> q;
int BFS( node start, node target)
{
int step = 0;
q.push(start); //从当前点开始
//visited.insert(node(start.x, start.y));
visited.insert(start);
while (!q.empty())
{
int sz = q.size();
for (int i=0;i<sz;i++)
{
// node cur = q.front();
//q.pop();
node cur = q.front();
q.pop();
if ((cur.x==target.x) &&(cur.y == target.y)) //判断是否到达target
return step;
for (int j = 0;j<4;j++)
{
node cur_temp(0,0);
cur_temp = plusOne(cur, j);
//( find(visited.begin(), visited.end(), x)!= visited.end()) &&
if (((cur_temp.x!= -1) && (cur_temp.y!=-1)) && Map[cur_temp.x][cur_temp.y]==0)
{
q.push(cur_temp);
node d = node(cur_temp.x,cur_temp.y);
//visited.insert(node(cur_temp.x, cur_temp.y));
//d.x = cur_temp.x;
//d.y = cur_temp.y;
visited.insert(d);
}
}
}
//划重点:更新步数在这里
step++;
}
}
int main(int argc, char * argv[])
{
//输入地图
/* for (int i = 0; i<5; i++)
for (int j = 0; j<5; j++)
cin >> Map[i][j];
*/
//Map[4][4] = 3; //定义终点
node start(0,0),target(4,4);
// start.x = 0;
// start.y = 0;
// target.x = 4;
// target.y = 4;
ans = BFS(start, target);
cout << ans << endl;
for(std::set<node>::iterator it=visited.begin() ;it!=visited.end();++it)
{
std::cout<<"x:"<<it->x<<",y:"<<it->y<<std::endl;
}
return 0;
}
//set 使用有问题