题目意思就是在一个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;
}
}
UVA439
最新推荐文章于 2021-05-20 10:21:59 发布