bfs 模板

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值