ZOJ 1091 BFS

广搜,由于要记录步数,所以又用到了滚动队列。

一开始没判断起点和终点在一起的情况,WA了一次


#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;

char ss[3], dd[3];
int map[9][9];
int dx, dy;
int point[8][2] = {{1, 2}, {1, -2}, {-1, -2}, {-1, 2}, {2, 1}, {2, -1}, {-2, 1}, {-2, -1}};
int ans;

struct Node {
	int xx, yy;
	Node() {}
	Node(int x, int y) {
		xx = x;
		yy = y;
	}
};
queue<Node> que[2];

void bfs() {
	Node tmp = que[0].front();
	int a, b;
	a = 0, b = 1;
	int s1, s2;
	s1 = tmp.xx;
	s2 = tmp.yy;
	memset(map, 0, sizeof(map));
	map[s1][s2] = 1;
	while(!que[a].empty()) {
		swap(a, b);
		ans++;
		while(!que[b].empty()) {
			tmp = que[b].front();
			que[b].pop();
			int a1, a2;
			a1 = tmp.xx;
			a2 = tmp.yy;
			map[a1][a2] = 0;
			for(int i = 0; i < 8; i++) {
				int xx = a1 + point[i][0];
				int yy = a2 + point[i][1];
				if(xx == dx && yy == dy) {
					return;
				}
				else if(xx >= 1 && xx <= 8 && yy >= 1 && yy <= 8) {
					map[xx][yy] = 1;
					que[a].push(Node(xx, yy));
				}
			}
		}
	}
}

int main() {
	while(scanf("%s%s", ss, dd) != EOF) {
		int sx, sy;
		ans = 0;
		sx = ss[0] - 'a' + 1;
		sy = ss[1] - '0';
		dx = dd[0] - 'a' + 1;
		dy = dd[1] - '0';
		if(sx == dx && sy == dy) {
			printf("To get from %s to %s takes 0 knight moves.\n", ss, dd);
			continue;
		}
		while(!que[0].empty()) que[0].pop();
		while(!que[1].empty()) que[1].pop();
		que[0].push(Node(sx, sy));
		bfs();
		printf("To get from %s to %s takes %d knight moves.\n", ss, dd, ans);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值