uva 439 Knight Moves 骑士移动 —— bfs
2017-03-03 20:08
393 查看
代码如下:
#include<stdio.h>//bfs 骑士的移动
#include<string.h>
#include<stdlib.h>
struct
{
int x,y,z;
}q[1000];
int map[10][10],head = 0, tail = 0;
int d[8][2]={ {-1,-2}, {-1,2}, {1,-2}, {1,2}, {-2,-1}, {-2,1}, {2,-1}, {2,1} };
int bfs(int x,int y,int xo,int yo)
{
if(x==xo && y==yo)
return 0;
q[tail].x = x; q[tail].y = y; tail++; map[x][y] = 1;
while(tail!=head)
{
for(int i = 0;i<8;i++)
{
int xx = q[head].x + d[i][0];
int yy = q[head].y + d[i][1];
if(!map[xx][yy] && xx>0 && xx<9 && yy>0 && yy<9)
{
if(xx==xo && yy==yo)
return q[head].z+1;
map[xx][yy] = 1;
q[tail].x = xx; q[tail].y = yy; q[tail].z = q[head].z+1; tail++;
}
}
head++;
}
return -1;
}
int main()
{
int x,y,xo,yo,step;
memset(map,0,sizeof(map));
memset(q,0,sizeof(q));
scanf("%d %d %d %d",&x,&y,&xo,&yo);
step = bfs(x,y,xo,yo);
step>=0? printf("%d",step):printf("no way");
return 0;
}
#include<stdio.h>//bfs 骑士的移动
#include<string.h>
#include<stdlib.h>
struct
{
int x,y,z;
}q[1000];
int map[10][10],head = 0, tail = 0;
int d[8][2]={ {-1,-2}, {-1,2}, {1,-2}, {1,2}, {-2,-1}, {-2,1}, {2,-1}, {2,1} };
int bfs(int x,int y,int xo,int yo)
{
if(x==xo && y==yo)
return 0;
q[tail].x = x; q[tail].y = y; tail++; map[x][y] = 1;
while(tail!=head)
{
for(int i = 0;i<8;i++)
{
int xx = q[head].x + d[i][0];
int yy = q[head].y + d[i][1];
if(!map[xx][yy] && xx>0 && xx<9 && yy>0 && yy<9)
{
if(xx==xo && yy==yo)
return q[head].z+1;
map[xx][yy] = 1;
q[tail].x = xx; q[tail].y = yy; q[tail].z = q[head].z+1; tail++;
}
}
head++;
}
return -1;
}
int main()
{
int x,y,xo,yo,step;
memset(map,0,sizeof(map));
memset(q,0,sizeof(q));
scanf("%d %d %d %d",&x,&y,&xo,&yo);
step = bfs(x,y,xo,yo);
step>=0? printf("%d",step):printf("no way");
return 0;
}
相关文章推荐
- UVa439---Knight Moves(BFS应用)
- uva 439 Knight Moves(BFS)
- uva439 - Knight Moves(BFS求最短路)
- UVa 439 - Knight Moves (BFS)
- UVA 439 骑士(Knight Moves ) 很基础的BFS
- 【UVA439】 Knight Moves BFS (3/1000)
- Knight Moves UVA - 439(BFS典例)
- UVa - 439 - Knight Moves(bfs求最短路)
- UVA 439 Knight Moves --DFS or BFS
- UVA 439-Knight Moves(bfs)
- UVA------439 - Knight Moves(bfs简单)
- uva 439 Knight Moves(BFS遍历)
- uva-439 - HDOJ-1372-Knight Moves-翻译详解-BFS
- UVA 439 Knight Moves 走象棋 (DFS or BFS)
- uva439 Knight Moves (搜索 BFS, BFS启蒙题)
- UVa 439/HDU 1372/POJ 2243/ZOJ 1091 Knight Moves(BFS&纯数学方法)
- UVa 439 - Knight Moves (BFS)
- UVa 439 Knight Moves(BFS应用)
- UVA439_Knight Moves(BFS)
- UVA 439 Knight Moves --DFS or BFS