哈尔滨理工大学软件与微电子学院程序设计竞赛(同步赛) C

Coronavirus

Coronavirus

题解

用数字代替字符,用二维数组存储地图,可以走的路用0表示。
在搜索之前对高位地段进行处理,九个格子全部表示为1。
BFS。
注意不要忘记标记遍历过的点。

AC代码

#include <bits/stdc++.h>

#define IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define mms(x, n) memset(x, n, sizeof(x))
#define INF (0x3f3f3f3f)
using namespace std;
const int N = 51;
int n, m;
int maze[N][N];
int sx, sy, ex, ey;
int d[N][N];
int v[N][N];
int f[4][2] = {
        {-1, 0},
        {1,  0},
        {0,  -1},
        {0,  1}
};
int ff[8][2] = {
        {-1, 0},
        {1,  0},
        {0,  -1},
        {0,  1},
        {-1, -1},
        {-1, 1},
        {1,  -1},
        {1,  1}
};

void init(int x, int y) {
    for (int i = 0; i < 7; i++) {
        int xx = x + ff[i][0], yy = y + ff[i][1];
        if (xx < 0 || xx > n || yy < 0 || yy > m) continue;
        maze[xx][yy] = 1;
    }
}

typedef pair<int, int> P;

int main() {
    IO;
    cin >> n >> m;
    mms(d, -1);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            char c;
            cin >> c;
            if (c == '*') {
                init(i, j);
            } else if (c == 'S') {
                sx = i, sy = j;
            } else if (c == 'E') {
                ex = i, ey = j;
            }
        }
    }
    queue<P> q;
    q.push(make_pair(sx, sy));
    d[sx][sy] = 0;
    v[sx][sy] = 1;
    while (!q.empty()) {
        P p = q.front();
        q.pop();
        int x = p.first, y = p.second;
        if (x == ex && y == ey) break;
        for (auto & i : f) {
            int xx = x + i[0], yy = y + i[1];
            if (xx < 0 || xx > n || yy < 0 || yy > m|| maze[xx][yy]==1 || v[xx][yy]==1) continue;
            v[xx][yy] = 1;
            q.push(make_pair(xx,yy));
            d[xx][yy] = d[x][y] + 1;
        }
    }
    int ans = d[ex][ey];
    if (ans==-1)cout << "Impossible";
    else cout << ans;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值