NYOJ 58 最少步数

链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=58

 

经典的迷宫问题,,,,用BFS穷举:

 

#include <iostream>
#include<queue>
#include<utility>
#include<cstdio>
#define N 9
using namespace std;
const int INF=1000000;
typedef pair<int,int> pt;
int dx[5]={1,0,-1,0};
int dy[5]={0,1,0,-1};
int sx,sy;
int gx,gy;
int d[10][10];
int maze[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 bfs()
{
    int i,j;
    int nx,ny;
    queue <pt> que;
    for(i=0;i<N;i++)
        for(j=0;j<N;j++)
        d[i][j]=INF;
    que.push(pt(sx,sy));
    d[sx][sy]=0;
    while(que.size())
    {
        pt p=que.front();
        que.pop();
        if(p.first==gx&&p.second==gy)       //如果取出的点是终点
            break;

        for(i=0; i<4; i++)
        {
            nx=p.first+dx[i];
            ny=p.second+dy[i];
            if(nx>=0&&ny>=0&&nx<N&&ny<N&&d[nx][ny]==INF&&maze[nx][ny]==0)
            {
                que.push(pt(nx,ny));
                d[nx][ny]=d[p.first][p.second]+1;
            }
        }

    }
    return d[gx][gy];


}
int main()
{

    freopen("1.txt","r",stdin);
    int t;
    cin>>t;
    int ans;
    while(t--)
    {
        cin>>sx>>sy>>gx>>gy;
        ans=bfs();
        cout<<ans<<endl;

    }
    return 0;
}


 

你可能感兴趣的:(OJ)