NYOJ 58 最少步数(bfs)

来源:互联网 发布:laydate.js报错 编辑:程序博客网 时间:2024/06/04 18:15

最少步数

时间限制:3000 ms  |  内存限制:65535 KB
难度:4
描述

这有一个迷宫,有0~8行和0~8列:

 1,1,1,1,1,1,1,1,1
 1,0,0,1,0,0,1,0,1
 1,0,0,1,1,0,0,0,1
 1,0,1,0,1,1,0,1,1
 1,0,0,0,0,1,0,0,1
 1,1,0,1,0,1,0,0,1
 1,1,0,1,0,1,0,0,1
 1,1,0,1,0,0,0,0,1
 1,1,1,1,1,1,1,1,1

0表示道路,1表示墙。

现在输入一个道路的坐标作为起点,再如输入一个道路的坐标作为终点,问最少走几步才能从起点到达终点?

(注:一步是指从一坐标点走到其上下左右相邻坐标点,如:从(3,1)到(4,1)。)

输入
第一行输入一个整数n(0<n<=100),表示有n组测试数据;
随后n行,每行有四个整数a,b,c,d(0<=a,b,c,d<=8)分别表示起点的行、列,终点的行、列。
输出
输出最少走几步。
样例输入
23 1  5 73 1  6 7
样例输出
1211

 

bfs,代码如下:

 

<span style="font-size:12px;">#include<cstdio>#include<cstring>#include<queue>using namespace std;int x,y,ex,ey,cnt,mark[10][10];int dir[4][2]={{1,0},{-1,0},{0,-1},{0,1}};int map[9][9]={ 1,1,1,1,1,1,1,1,1, 1,0,0,1,0,0,1,0,1, 1,0,0,1,1,0,0,0,1, 1,0,1,0,1,1,0,1,1, 1,0,0,0,0,1,0,0,1, 1,1,0,1,0,1,0,0,1, 1,1,0,1,0,1,0,0,1, 1,1,0,1,0,0,0,0,1, 1,1,1,1,1,1,1,1,1,};struct node{int x,y,step;}a,temp;int cmp(node temp){if(temp.x<0||temp.x>8)   return 0;if(temp.y<0||temp.y>8)   return 0;if(mark[temp.x][temp.y]||map[temp.x][temp.y])   return 0;if(temp.step>=cnt)   return 0;return 1;}void bfs(){int i;a.x=x;a.y=y;a.step=0;memset(mark,0,sizeof(mark));queue<node>q;mark[x][y]=1;q.push(a);while(!q.empty()){a=q.front();q.pop();for(i=0;i<4;i++){temp.x=a.x+dir[i][0];temp.y=a.y+dir[i][1];temp.step=a.step+1;if(cmp(temp)){if(temp.x==ex&&temp.y==ey){if(cnt>temp.step)   cnt=temp.step;continue;}mark[temp.x][temp.y]=1;q.push(temp);}}}}int main(){int t;scanf("%d",&t);while(t--){scanf("%d%d%d%d",&x,&y,&ex,&ey);if(x==ex&&y==ey){printf("0\n");continue;}cnt=100;bfs();printf("%d\n",cnt);}return 0;}</span>


 

0 0
原创粉丝点击