# c++实现广度优先搜索（BFS）

int maze[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,
};

``````#include<math.h>
#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
#include<queue>

#define MAXL 5

using namespace std;

bool isValid(vector<vector<int> >& maze, int x, int y){
return !maze[x][y];
}

bool maze_search(vector<vector<int> >& maze, vector<int>& vs, vector<int>& vd){
queue<vector<int> > qvec;

bool visit[MAXL][MAXL];
for (int i = 0; i < MAXL; i++) {
for (int j = 0; j < MAXL; j++) {
visit[i][j] = false;
}
}

int dir[][2] = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};

qvec.push(vs);
visit[vs[0]][vs[1]] = true;

while(!qvec.empty()){
vector<int> vn;
vn = qvec.front();
qvec.pop();

for(int i=0; i<4; i++){
int vx = vn[0] + dir[i][0];
int vy = vn[1] + dir[i][1];

if(vx==vd[0] && vy==vd[1])
return true;

if((vx>=0 && vx<MAXL && vy>=0 && vy<MAXL) && isValid(maze, vx, vy) && !visit[vx][vy]){
vector<int> tmp;
tmp.push_back(vx);
tmp.push_back(vy);
qvec.push(tmp);
visit[vx][vy] = true;
}
}
}
return false;
}

void display_2_vector(vector<vector<int> > ivec){
for(int i=0; i<ivec.size(); i++){
for(int j=0; j<ivec[0].size(); j++){
cout<< ivec[i][j]<< " ";
}
cout<<endl;
}

}

int main(void)
{
int a[MAXL][MAXL] = {{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}};
vector<vector<int> > maze(MAXL, vector<int>(MAXL));
for(int i=0; i<MAXL; i++){
for(int j=0; j<MAXL; j++){
maze[i][j] = a[i][j];
}
}

vector<int> vs(2, 0);
vector<int> vd(2, 4);

cout<<maze_search(maze, vs, vd)<<endl;

display_2_vector(maze);

}
``````
原文作者：BFS
原文地址: https://www.cnblogs.com/majianqiang/p/8533485.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。