【a803】营救

Time Limit: 10 second
Memory Limit: 2 MB

问题描述
铁达尼号遇险了!它发出了求救信号。距离最近的哥伦比亚号收到了讯息,时间就是生命,必须尽快赶到那里。通过侦测,哥伦比亚号获取了一张海洋图。这张图将海洋部分分化成n*n个比较小的单位,其中1标明的是陆地,用0标明的是海洋。船只能从一个各自移到相临的四个格子。为了尽快赶到出事地点,哥伦比亚号最少需要走多远的距离。

Input

第一行为n,下面是一个n*n的0,1矩阵,表示海洋地图。最后一行为四个小于n的整数,分别表示哥伦比亚号和铁达尼号的位置。

Output

哥伦比亚号到铁达尼号的最短距离,答案精确到整数。


Sample Input

3
001
101
100
1 1 3 3

Sample Output

4

【题解】

最短距离这类问题,可以用广搜来实现,因为广搜就是查看当前下一步可以走的所有情况,当所有情况都考虑到了,再 走下一步,即一层一层地搜索。如果遇到了终点,那这样的走法一定是最快的。遇到终点直接输出答案即可。

【代码】

#include <cstdio>
#include <iostream>
 
const int dx[5] = {0,0,0,1,-1}; //用于扩展结点。
const int dy[5] = {0,1,-1,0,0};
 
int n,x1,yy1,x2,yy2,dl[2000000][3]; //dl表示队列 [i][0] 和 [i][1]用来存坐标 [2]用来存当前走的步数 dl[1000000][3]占用了11MB
bool a[2010][2010]; //用来存储地图信息 这个数组只占了 1MB不到
 
using namespace std;
 
void input_data()
{
    scanf("%d",&n);
    for (int i = 1;i <= n;i++)
        {
            for (int j = 1;j<= n;j++)
            {
                char t;
                cin >> t;
                if (t=='0')
                    a[i][j] = true;
            }
 
        }
    scanf("%d%d%d%d",&x1,&yy1,&x2,&yy2); //输入起点和终点。
}
 
void bfs(int x,int y) //从x,y起点开始搜索
{
    int head =1,tail = 1; //头结点和尾节点
    dl[1][0] = x;dl[1][1] = y;dl[1][2] = 0; //将第一个点入队
    //a[x][y] = false;
    while (head <= tail)
        {
            int xx = dl[head][0],yy = dl[head][1],tt = dl[head][2]; //取出头结点
            head++;
            for (int i = 1;i <= 4;i++) //往4个方向扩展
                {
                    int tx = xx + dx[i],ty = yy + dy[i];
                    if (tx < 1) continue; //如果越界或者是陆地 活着已经走过 就不用走了。
                    if (tx > n) continue;
                    if (ty < 1) continue;
                    if (ty > n) continue;
                    if (a[tx][ty]) //如果可以走就走
                        {
                            a[tx][ty] = false;
                            dl[++tail][0] = tx;dl[tail][1] = ty;dl[tail][2] = tt + 1; //并记录在队列中 便于后续的扩展
                            if ( (tx == x2) && (ty == yy2)) //根据广搜的性质,可以一找到终点就输出。
                                {
                                    printf("%d
",dl[tail][2]);
                                    return;
                                }
                        }
                }
        }
}
 
void get_ans()
{
    bfs(x1,yy1);
}
 
int main()
{
    input_data();
    get_ans();
    return 0;
}


原文地址:https://www.cnblogs.com/AWCXV/p/7632445.html