您的位置:首页 > 其它

NYoj 58 最小的步数 (BFS

2017-03-22 16:27 176 查看

最少步数

时间限制: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

#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
#define N 1000
bool vis

;
int dir[4][2] = {0,1,0,-1,1,0,-1,0};
int m, n, sx, sy, ex, ey;
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; int y; int step;
bool friend operator<(node a,node b) {
return a.step > b.step;          // 最小堆
}
}st,mid,ne;
bool judge(int x,int y)
{
if(x>=0 && x<9 && y>=0 && y<9)
return true;
else
return false;
}
int bfs()
{
priority_queue<node> fq;
st.x = sx; st.y = sy; st.step = 0;
fq.push(st);
vis[sx][sy] = true;
while(!fq.empty()) {
mid = fq.top();
fq.pop();
if(mid.x==ex && mid.y==ey) return mid.step;
for(int i = 0;i < 4; i++) {
ne.x = mid.x + dir[i][0];
ne.y = mid.y + dir[i][1];
if(ne.x==ex && ne.y==ey)
return mid.step + 1 ;
if(judge(ne.x,ne.y) && map[ne.x][ne.y]!=1 && !vis[ne.x][ne.y]) {
ne.step = mid.step + 1;
vis[ne.x][ne.y] = true;
fq.push(ne);
}
}
}
return 0;
}

int main()
{
int T;
scanf("%d",&T);
while(T--) {
scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
memset(vis,false,sizeof(vis));
int k = bfs();   printf("%d\n",k);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: