Niuke.com - [11th program design competition of Beijing University of information technology] kotori and maze (BFS)

Links: https://ac.nowcoder.com/acm/contest/940/D
Source: niuke.com
Time limit: 1 second for C / C + + and 2 seconds for other languages
Space limit: C/C++ 32768K, other languages 65536K
64bit IO Format: %lld

Title Description

kotori is in a n*m maze. The outermost layer of the maze is submerged by magma and cannot be touched. There are k exits in the maze. kotori can only move up, down, left and right. She wants to know how many exits she can reach and how far is the nearest exit from her?

Input description

The first line is two integers n and m, representing the number of rows and columns in the maze (1 ≤ n,m ≤ 30).
It is followed by a string of n lines of m length to describe the maze. 'k' represents the location where kotori starts, '.' represents the road, '*' represents the wall, 'e' represents the exit. Ensure the input is legal.

Output description

If an exit can be reached, two integers are output, the first representing the number of exits kotori can choose, and the second representing the steps from kotori to the nearest exit. (note that kotori will leave the maze when it reaches the exit.)
If there is no exit to reach, output - 1.

input

6 8
e.*.*e.*
.**.*.*e
..*k**..
***.*.e*
.**.*.**
*......e

output

2 7

Explain

The available coordinates are [4,7] and [6,8], and the distance to kotori is 8 and 7 steps respectively.

Solving problems

Ask the number of exits you can reach and the distance to the nearest exit.
Thinking: BFS.

Accepted Code:

#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
struct edge {
    int x, y, t;
}p;
char mp[35][35];
int n, m, cnt = 0, min_ = inf, vis[35][35];
int arr[4][2] = {{1, 0}, {0, 1}, {0, -1}, {-1, 0}}; 
void BFS(int x, int y) {
    int tx, ty;
    queue <edge> Q;
    Q.push((edge){x, y});
    while (!Q.empty()) {
        p = Q.front();
        Q.pop();
        if (mp[p.x][p.y] == 'e') {
            cnt++;
            min_ = min(min_, p.t);
            continue;
        }
        for (int i = 0; i < 4; i++) {
            tx = p.x + arr[i][0];
            ty = p.y + arr[i][1];
            if (tx >= 0 && tx < n && ty >= 0 && ty < m && !vis[tx][ty] && mp[tx][ty] != '*'){
                vis[tx][ty] = true;
                Q.push((edge){tx, ty, p.t + 1});
            }
        }
    }
}
int main() {
    int ex, ey;
    scanf("%d%d", &n, &m);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            scanf(" %c", &mp[i][j]);
            if (mp[i][j] == 'k')
                ex = i, ey = j;
        }
    }
    BFS(ex, ey);
    if (min_ < inf)
        printf("%d %d\n", cnt, min_);
    else printf("-1\n");
    return 0;
}

Posted by mccdave on Sat, 02 Nov 2019 02:36:26 -0700