概述
20180605 一
/*bfs模板题第一次*/
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
int m, n, x1, x2, y1, y2;
int vis[25][25];
int dir[8][2] = {{1,2}, {2,1}, {2,-1}, {1,-2},
{-1,-2},{-2,-1}, {-2,1}, {-1,2}};
struct node {
int x;
int y;
int num;
};
node begin, end;
int ok(int a, int b) {
if(a >= 1 && a <= n && b >= 1 && a <= m) {
return true;
} else {
return false;
}
}
int bfs(node now) {
queue<node> q;
q.push(nom);
vis[now.x][now.y] = 1;
node help, help1;
while(!q.empty()) {
help = q.front();
q.pop();
for(int i = 0; i < 8; i++) {
help1.x = help.x + dir[i][0];
help1.y = help.y + dir[i][1];
help1.num = help.num + 1;
if(help1.x == end.x && help1.y == end.y) {
return help1.num;
}
if(!vis[help1.x][help1.y] && ok(help1.x, help1.y)) {
q.push(help1);
vis[help1.x][help1.y] = 1;
}
}
}
return -1;
}
int main() {
while(cin>>n>>m>>x2>>y2>>x1>>y1) {
memset(vis,0,sizeof(vis));
begin.x = x1;
begin.y = y1;
begin.num = 0;
end.x = x2;
end.y = y2;
cout<<bfs(begin)<<endl;
}
return 0;
}
20180606 二刷
/*20180606 二刷*/
/*明天高考了,祝所有考生考出好成绩*/
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
int m, n, x1, x2, y1, y2;
int vis[25][25];
int dir[8][2] = {{1,2}, {2,1}, {2,-1}, {1,-2},
{-1,-2}, {-2,-1}, {-2,1}, {-1,2}};
struct node{
int x;
int y;
int num;
};
node begin, end;
bool ok(int a, int b) {
if(a >= 1 && a <= n && b >= 1 && b <= m) {
return true;
} else {
return false;
}
}
int bfs(node now) {
queue<node> q;
q.push(now);
vis[now.x][now.y] = 1;
node help, help1;
while(!q.empty()) {
help = q.front();
q.pop();
for(int i = 0; i < 8; i++) {
help1.x = help.x + dir[i][0];
help1.y = help.y + dir[i][1];
help1.num = help.num + 1;
if(help1.x == end.x && help1.y == end.y) {
return help1.num;
}
if(!vis[help1.x][help1.y] && ok(help1.x, help1.y)) {
q.push(help1);
vis[help1.x][help1.y] = 1;
}
}
}
return -1;
}
int main() {
while(cin>>m>>n>>x2>>y2>>x1>>y1) {
memset(vis, 0, sizeof(vis));
begin.x = x1;
begin.y = y1;
end.x = x2;
end.y = y2;
cout<<bfs(begin)<<endl;
}
return 0;
}
最后
以上就是懵懂水蜜桃为你收集整理的bfs 模板的全部内容,希望文章能够帮你解决bfs 模板所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复