第一章、BFS的自我介绍;
我是BFS我生活在函数大家庭中,我是DFS的弟弟,我与DFS的性格不一样,我干什么都一起干,最后一起干完!
第二章、用法;
我是用来求最短路的,如图:
就像这样,我和DFS一样也有模板 :
queue<数据类型> q;
while(!q.empty){
int head=q.front();
q.pop();
for(枚举)
if(合法)
q.push();
}
第三章、上题目;
一道水题,先尝试在看!code:
#include<bits/stdc++.h>
using namespace std;
const int N=400;
int n,m,sx,sy;
struct horse{
int x,y;
};
int mx[]={0,2,1,-1,-2,-1,-2,2,1};
int my[]={0,1,2,-2,-1,2,1,-1,-2};
queue<horse> q;
bool vis[N][N];
int ans[N][N];
void bfs(){
q.push(horse{sx,sy});
vis[sx][sy]=true;
ans[sx][sy]=0;
while(!q.empty()){
horse head=q.front();q.pop();
for(int i=1;i<=8;i++){
int hx=head.x+mx[i];
int hy=head.y+my[i];
if(hx<1||hy<1||hx>n||hy>m||vis[hx][hy]) continue;
q.push(horse{hx,hy});
ans[hx][hy]=ans[head.x][head.y]+1;
vis[hx][hy]=true;
}
}
}
int main(){
cin>>n>>m>>sx>>sy;
memset(ans,-1,sizeof(ans));
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
bfs();
cout<<ans[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
很简单!;再来一道!
这就是一道典型的BFS,CODE:
#include<bits/stdc++.h>
using namespace std;
const int N = 210;
int n, a, b;
int mv[3] = {0, 1, -1};
int k[N];
queue<int> Q;
bool vis[N];
int dist[N];
int main() {
cin >> n >> a >> b;
for (int i = 1; i <= n; i++) {
cin >> k[i];
}
for (int i = 1; i <= n; i++) {
dist[i] = -1;
}
Q.push(a);
vis[a] = true;
dist[a] = 0;
while (!Q.empty()) {
int head = Q.front();
Q.pop();
for (int i = 1; i <= 2; i++) {
int dx = head + mv[i] * k[head];
if (dx < 1 || dx > n || vis[dx]) {
continue;
}
Q.push(dx);
vis[dx] = true;
dist[dx] = dist[head] + 1;
}
if (head == b) {
break;
}
}
cout<<dist[b];
return 0;
}
虽然没用BFS函数,但有BFS的基础逻辑;