poj 1915 bfs(骑士移动)
2012-01-18 01:28
417 查看
题意:给出棋盘上的初始点和终止点,求初始点到达终止点的最小步数。
思路:广搜求图上的最短步数,何为最短?就是每走一步都保证是往树的下一层走,那么到达终点的时候需要的步数就是最少的。那么就每走一个点就把下一次可能跳过的所有点的步数都加一,最后输出终止点存的步数即可。
#include<iostream> #include<stdlib.h> using namespace std; int dir[8][2]={{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}}; //八个方向。TMD方向数组打错了 一直runtime error想想就恶心 int step[305][305],map[305][305],l,xx[90005],yy[90005]; //到达点所需的最少步数,标记数组,横纵坐标队列 void bfs(int i,int j) { int front,rear,k,x,y;//队列头、队列尾 front=0;rear=0; step[i][j]=0; map[i][j]=1; xx[rear]=i;yy[rear++]=j; while(front<rear) { //printf("队列头:%d 队列尾:%d\n",front,rear); i=xx[front];j=yy[front++]; //printf("x=%d,y=%d \n",i,j); for(k=0;k<8;k++) { x=i+dir[k][0]; y=j+dir[k][1]; if(!map[x][y]&&x>=0&&x<l&&y>=0&&y<l) { //图上的点 是从0开始的 所以 x,y>=0; map[x][y]=1; step[x][y]=step[i][j]+1;//扩展一层,加一 //printf("%d=%d+1",step[x][y],step[i][j]); //system("pause"); xx[rear]=x;yy[rear++]=y; } } } } int main() { int n,sx,sy,ex,ey; scanf("%d",&n); while(n--) { scanf("%d",&l); scanf("%d%d",&sx,&sy); scanf("%d%d",&ex,&ey); memset(map,0,sizeof(map)); memset(step,0,sizeof(step)); if(sx==ex&&sy==ey) { printf("0\n"); continue; } bfs(sx,sy); printf("%d\n",step[ex][ey]); } //system("pause"); return 0; }
[/code]
相关文章推荐
- poj 2243 bfs(还是骑士移动)
- POJ 1915 Knight Moves (经典的BFS) --from lanshui_Yang
- UVA 439 BFS 骑士的移动
- [BFS]poj 1915 Knight Moves
- POJ 题目1915 Knight Moves(双向BFS)
- POJ 1915 BFS题目
- poj 1915 BFS
- POJ1915 BFS&双向BFS
- uva 439 Knight Moves(骑士的移动)BFS
- POJ1915 BFS
- poj 1915 Knight Moves 【双向bfs】
- poj 1915 Knight Moves(BFS)
- 路径问题系列之 POJ 1915 Knights Moves(BFS)
- POJ1915 BFS&双向BFS
- POJ 1915-Knight Moves(BFS-跳马)
- poj 1915 BFS
- poj1915 bfs
- poj1915 Knight Moves(BFS)
- poj 1915//简单bfs
- (未)poj1915(bfs)