您的位置:首页 > 其它

hdu1372 Knight Moves(马步bfs水)

2016-03-05 10:35 344 查看
仅仅是变成8个方向而已。

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

const int N = 20;
const int INF = 1000000;

bool vis

;

int dir[8][2] = {{-2, 1}, {-2, -1}, {-1, 2}, {-1, -2}, {1, 2}, {1, -2}, {2, 1}, {2, -1}};

struct node
{
int x, y;
int step;
};

node st, ed;

bool check(int x, int y)
{
if(x >= 0 && x < 8 && y >= 0 && y < 8 && !vis[x][y]) return true;
else return false;
}

int bfs(int x, int y)
{
queue <node> q;
node s_pos;
s_pos.x = x;
s_pos.y = y;
s_pos.step = 0;
if(x == ed.x && y == ed.y) return s_pos.step;
vis[s_pos.x][s_pos.y] = 1;
q.push(s_pos);
while(!q.empty())
{
node tmp = q.front();
q.pop();
for(int i = 0; i < 8; i ++)
{
node tmp2;
tmp2 = tmp;
tmp2.x += dir[i][0];
tmp2.y += dir[i][1];
tmp2.step += 1;
if(check(tmp2.x, tmp2.y))
{
if(tmp2.x == ed.x && tmp2.y == ed.y) return tmp2.step;
vis[tmp2.x][tmp2.y] = 1;
q.push(tmp2);
}
}
}
return 0;
}

int main()
{
// freopen("in.txt", "r", stdin);
char s1[5], s2[5];
while(~scanf("%s %s", s1, s2))
{
st.x = s1[0] - 'a';
st.y = s1[1] - '1';
ed.x = s2[0] - 'a';
ed.y = s2[1] - '1';
memset(vis, 0, sizeof(vis));
printf("To get from %s to %s takes %d knight moves.\n", s1, s2, bfs(st.x, st.y));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hdu