NYOJ 题目58 最小步数
2016-02-07 14:36
337 查看
最少步数
时间限制: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)分别表示起点的行、列,终点的行、列。
输出输出最少走几步。
样例输入
2 3 1 5 7 3 1 6 7
样例输出
12 11
基本的广搜。
#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
struct node{
int x,y;
int step;
};//加入队列的结点
queue<struct node> q;
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 direction[4][2]={1,0,-1,0,0,1,0,-1};//四个方向
bool visited[9][9];
void init_queue(){//初始化队列
while(!q.empty()){
q.pop();
}
}
int bfs(int x1,int y1,int x2,int y2){//广搜
struct node a={x1,y1,0};//先创建一个起点结点,步数设为0
q.push(a);//起点先入队列
visited[x1][y1]=1;
while(!q.empty()){
a=q.front();//将队头元素赋值给a
if(a.x==x2&&a.y==y2)break;//如果找到终点,退出循环
q.pop();//队头元素出队列
for(int i=0;i<4;i++){
int x=a.x+direction[i][0];
int y=a.y+direction[i][1];
if(x>=0&&x<=8&&y>=0&&y<=8&&!visited[x][y]&&map[x][y]==0){//满足各种条件
visited[x][y]=1;
struct node aa={x,y,a.step+1};
q.push(aa);//入队列
}
}
}
if(q.empty())return 0;//如果队列为空,即永远找不到终点
return a.step;
}
int main(){
int cases,i,j;
cin>>cases;
int x1,y1,x2,y2;
while(cases--){
cin>>x1>>y1>>x2>>y2;
init_queue();
memset(visited,0,sizeof(visited));
int min_step=bfs(x1,y1,x2,y2);
cout<<min_step<<endl;
}
return 0;
}
相关文章推荐
- 简单的四则运算
- 数的奇偶性
- ACM网址
- 1272 小希的迷宫
- 1272 小希的迷宫
- hdu 1250 大数相加并用数组储存
- 矩阵的乘法操作
- 蚂蚁爬行问题
- 蚂蚁爬行问题
- 求两个数的最大公约数【ACM基础题】
- 打印出二进制中所有1的位置
- 杭电题目---一只小蜜蜂
- HDOJ 1002 A + B Problem II (Big Numbers Addition)
- 初学ACM - 半数集(Half Set)问题 NOJ 1010 / FOJ 1207
- 初学ACM - 组合数学基础题目PKU 1833
- POJ ACM 1002
- POJ 2635 The Embarrassed Cryptographe
- POJ 3292 Semi-prime H-numbers
- POJ 2773 HAPPY 2006
- POJ 3090 Visible Lattice Points