UVA439

题目意思就是在一个8 × 8 的棋盘上,a代表1,b代表2这样。。
然后从一个位置移动到另一个位置,最少要几步;
国际象棋中的骑士,和象棋中的马是一样的,走日字;;
用bfs()搜一边。。



#include<stdio.h>
#include<queue>
#include<iostream>
#include<string>
using namespace std;

const int N = 20;
int bx,by;
int ex,ey;
bool cheer[N][N];
int pos[N * N];
bool vis[N][N];
struct squ {
	int x;
	int y;
	int dis;
}p1,p2;
int cx[8] = {-2,-2,2,2,-1,1,-1,1};
int cy[8] = {-1,1,-1,1,2,2,-2,-2};
queue<squ> q;
bool ok;
int res;
void init() {

	for (int i = 0 ; i < N ;i++) {
		for (int  j = 0; j < N; j++) {
			cheer[i][j] = false;
			vis[i][j] = false;
		}
	}
	for (int i = 0 ; i < N * N ; i++) {
		pos[i] = i - 96;
	}
	while(!q.empty())
		q.pop();
	ok = false;
	res = 0;
}
bool canbe(int x,int y) {
	if(x < 1 || y < 1 || x > 8 || y > 8 ||vis[x][y] == true)
		return false;
	return true;
}
void bfs() {
	p1.x = bx;
	p1.y = by;
	p1.dis = 0;
	q.push(p1);
	vis[bx][by] = true;
	while(!q.empty()) {
		p1 = q.front();
		q.pop();
		int x = p1.x;
		int y = p1.y;
		int s = p1.dis;
		for (int i = 0 ; i < 8 ;i++) {
			int x1 = x + cx[i];
			int y1 = y + cy[i];
			if (canbe(x1,y1)) {
				if ( x1 == ex && y1 == ey) {
					ok = true;
					res = s + 1;
					break;
				}
				vis[x1][y1] = true;
				p2.x = x1;
				p2.y = y1;
				p2.dis = s + 1;
				q.push(p2);
			}
		}
			if (ok == true)
				break;

	}

}
int main () {
	string str;
	while (getline (cin ,str)) {
		init();
		bx = pos[str[0]];
		by = str[1] - 48;
		ex = pos[str[3]];
		ey = str[4] - 48;
		bfs();
		cout <<"To get from " << str[0] << str[1] <<" to "<<str[3] <<str[4] << " takes "<<res<<" knight moves." <<endl;
	}


}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值