bfs 模板

20180605 一

/*bfs模板题第一次*/
#include 
#include 
#include 
#include 
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 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<

20180606 二刷

/*20180606 二刷*/
/*明天高考了,祝所有考生考出好成绩*/
#include 
#include 
#include 
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 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 模板)