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;
}
#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 5366】The mook jong 详解
- 【HDU 2136】Largest prime factor 详细图解
- HDU 1568
- HDU1290
- HDU1568(Fobonacci公式)
- HDU ACM Step 2.2.2 Joseph(约瑟夫环问题)
- HDU 1405
- HDU 1297
- hdu 1205
- hdu 2087
- hdu 1016
- HDU 4898 The Revenge of the Princess’ Knight ( 2014 Multi-University Training Contest 4 )
- HDU 5592 ZYB's Premutation 线段树(查找动态区间第K大)
- HDU 5240 Exam (好水的题)
- HDU5237 Base64 大模拟
- HDU 1000
- HDU 1001
- 2015-11-11 hdu新生赛 A题(AC)
- 2015-11-11 hdu新生赛 C题(结束后一发AC)
- 2015-11-11 hdu新生赛 E题(结束后一发AC)