南阳理工58最少步数

来源:互联网 发布:安卓framework源码 编辑:程序博客网 时间:2024/06/09 19:09
最少步数
时间限制: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
来源
[苗栋栋]原创
上传者
苗栋栋

题意分析:这是最简单的搜索问题,用的是BFS,唯一注意的一点就是,当输入为两个点相等时,应该输出为0

#include<iostream>#include<stdio.h>#include<queue>using namespace std;int dx[]={1,0,0,-1};int dy[]={0,1,-1,0};struct dot{    int x,y;    int time;};inline bool in(dot gx){    if(gx.x>=0&&gx.x<9&&gx.y>=0&&gx.y<9)        return true;    return false;}int main(){    int vis[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 test;    int x1,x2,y1,y2;    cin>>test;    while(test--)    {        dot gx;        cin>>x1>>y1>>x2>>y2;        if(x1==x2&&y1==y2)            cout<<0<<endl;        else        {        gx.x=x1;        gx.y=y1;        gx.time=0;        queue<dot>q;        while(!q.empty())            q.pop();        q.push(gx);        int step=0;        while(!q.empty())        {            dot next,tmp;            tmp=q.front(),q.pop();            for(int i=0;i<4;i++)            {                next.x=tmp.x+dx[i];                next.y=tmp.y+dy[i];                next.time=tmp.time+1;                if(in(next)&&!vis[next.x][next.y])                {                    q.push(next);                    if(next.x==x2&&next.y==y2)                    {                        step=next.time;                        break;                    }                }            }            if(step>0)                break;        }        cout<<step<<endl;    }    }    return 0;}


0 0
原创粉丝点击