zoukankan      html  css  js  c++  java
  • 营救 【题解】

    营救:

    内存限制:256 MiB 
    时间限制:1000 ms
    

    题目描述:

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

    输入格式

    第一行为 n,下面是一个 n*n 的 0、1 矩阵,表示海洋地图。
    
    最后一行为四个小于 n 的整数,分别表示哥伦比亚号和铁塔尼号的位置。
    输出格式
    
    哥伦比亚号到铁塔尼号的最短距离,答案精确到整数。
    

    样例输入 :

    3
    001
    101
    100
    1 1 3 3
    

    样例输出

    4
    

    这道题其实并不难,就是一道简单的广搜。注释都写到代码上了。

    #include <cstdio>
    #include <cstring>
    #include <queue>
    using namespace std;
    
    const int MAXN = 1005;
    const int dx[] = { 0, 1, -1, 0, 0 };
    const int dy[] = { 0, 0, 0, 1, -1 };//方向数组
    
    int s, t, ss, tt, n;
    int ans = 0x3f3f3f3f;//极大值,用于查找最小值
    bool map[MAXN][MAXN];//储存地图
    
    struct node {
        int x;
        int y;
        int step;
    };//两个坐标,一个是步数
    
    void search_(int x, int y) {
        node p, t;
        p.x = x;
        p.y = y;
        p.step = 0;//初始化
        queue<node> q;
        q.push(p);
        while (!q.empty()) {//搜索
            p = q.front();
            if (p.x == ss && p.y == tt) {
                ans = min(p.step, ans);
                break;
            }//符合条件,找到答案并跳出循环
            for (int i = 1; i <= 4; i++) {
                t.x = p.x + dx[i];
                t.y = p.y + dy[i];//四个方向枚举怎么走
                if (t.x > 0 && t.x <= n && t.y > 0 && t.y <= n && !map[t.x][t.y]) {//此步合法
                    map[t.x][t.y] = 1;//就走这步
                    t.step = p.step + 1;//增加一步
                    q.push(t);//继续搜索
                }
            }
            q.pop();//弹出队首,继续下一次循环
        }
    }
    int main() {
        scanf("%d", &n);
        for (int i = 1; i <= n; i++) {
            scanf("
    ");
            for (int j = 1; j <= n; j++) {
                char x;
                scanf("%c", &x);
                map[i][j] = x - '0';
            }
        }//初始化
        scanf("%d %d %d %d", &s, &t, &ss, &tt);//输入
        search_(s, t);
        printf("%d
    ", ans);//输出答案
        return 0;
    }
    
    
  • 相关阅读:
    Web容器中DefaultServlet详解
    MySQL笔记(四)DDL与DML风格参考
    MySQL笔记(三)由txt文件导入数据
    MySQL Crash Course #21# Chapter 29.30. Database Maintenance & Improving Performance
    MySQL Crash Course #20# Chapter 28. Managing Security
    Linux笔记 #07# 搭建机器学习环境
    Google's Machine Learning Crash Course #03# Reducing Loss
    MySQL Crash Course #19# Chapter 27. Globalization and Localization
    MySQL Crash Course #18# Chapter 26. Managing Transaction Processing
    MySQL Crash Course #17# Chapter 25. 触发器(Trigger)
  • 原文地址:https://www.cnblogs.com/cqbzyanglin/p/13509279.html
Copyright © 2011-2022 走看看