牛客网-牛牛游玩记

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/PZHU_CG_CSDN/article/details/80873765

链接:https://www.nowcoder.com/questionTerminal/64a9bb7cdaa04df9896c7d26192bed63?orderByHotValue=1&page=1&onlyReference=false
来源:牛客网

又是晴朗的一天,牛牛的小伙伴们都跑来找牛牛去公园玩。但是牛牛想呆在家里看E3展,不想出去逛公园,可是牛牛又不想鸽掉他的小伙伴们,于是找来了公园的地图,发现公园是由一个边长为n的正方形构成的,公园一共有m个入口,但出口只有一个。公园内有一些湖和建筑,牛牛和他的小伙伴们肯定不能从他们中间穿过,所以只能绕行。牛牛想知道他需要走的最短距离并输出这个最短距离。

输入描述:

第一行输入一个数字n(1≤n≤1000)表示公园的边长
接下来会给你一个n*n的公园地图,其中 . 表示公园里的道路,@表示公园的入口,*表示公园的出口,#表示公园内的湖和建筑。牛牛和他的小伙伴们每次只能上下左右移动一格位置。
输入保证公园入口个数m(1≤m≤10000)且所有的入口都能和出口相连。

输出描述:

输出牛牛需要行走的最短距离。

示例:

输入

10
.@....##@.
......#...
...@..#...
###.......
....##..#.
...####...
@...##....
#####.....
..##*####.
#.........

输出

16

分析:就是一个搜索题,只不过起点有多个,逆向思维:将终点作为起点,起点当终点,这样从终点开始 BFS 找到一个起点就是最终答案。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
#include <queue>
using namespace std;
char G[1005][1005];
int dx[] = {-1,1,0,0};//定义方向
int dy[] = {0,0,-1,1};
int visit[1005][1005];
int n;
struct node{
    int x,y;
    int step;
    node(){}
    node(int x1,int y1,int step1){
        x = x1;
        y = y1;
        step = step1;
    }
};
bool check(int x,int y){
    if(x < 0 || x >= n || y < 0 || y >= n) return false;
    if(G[x][y] == '#') return false;
    if(visit[x][y] == 1) return false;
    return true;
}
int bfs(node s){
    queue<node> q;
    q.push(s);
    memset(visit,0,sizeof(visit));

    visit[s.x][s.y] = 1;

    while(!q.empty()){
        node cur = q.front();
        q.pop();

        if(G[cur.x][cur.y] == '@') return cur.step;

        for(int i = 0;i < 4;i++){
            int X = cur.x + dx[i];
            int Y = cur.y + dy[i];

            if(!check(X,Y)) continue;

            node next = node(X,Y,cur.step+1);
            visit[X][Y] = 1;//标记已访问
            q.push(next);
        }
    }
}
int main(void){

    cin>>n;
    node s;
    for(int i = 0;i < n;i++)
        for(int j = 0;j < n;j++){
            cin>>G[i][j];
            if(G[i][j] == '*')
                s = node(i,j,0);
        }

    int count = bfs(s);
    cout<<count<<endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/PZHU_CG_CSDN/article/details/80873765