您的位置:首页 > 其它

nyoj58最小步数——BFS

2018-03-27 17:08 495 查看
最小步数

最少步数

时间限制: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 <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <queue>
#define maxn 1001
using namespace std;
int start_x,start_y,end_x,end_y;
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};
int book[9][9];
int Next[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
struct Node{
int x,y,step;
Node(){}
Node(int x,int y):x(x),y(y){}
Node(int x,int y,int step):x(x),y(y),step(step){}
};
int ans = 0;
int bfs(){
int nx,ny;
queue <Node>que;
que.push(Node(start_x,start_y,0));
book[start_x][start_y] = 1;
while(!que.empty()){
Node head = que.front();
que.pop();
for(int k=0;k<4;k++){
nx = head.x + Next[k][0];
ny = head.y + Next[k][1];
if(nx>=0 && ny>=0 && nx<9 && ny<9 && map[nx][ny]==0 && book[nx][ny] == 0){
que.push(Node(nx,ny,head.step+1));
book[nx][ny] = 1;
}
if(que.back().x == end_x && que.back().y == end_y)
return que.back().step;
}
}
return 0;
}
int main(){
//    freopen("/Users/zhaohaibo/Desktop/a.txt","r",stdin);
int ncase;
cin>>ncase;
while(ncase--){

memset(book,0,sizeof(book));
cin>>start_x>>start_y>>end_x>>end_y;
cout<<bfs()<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: