【笔试】对称飞行器

题目链接

BFS,就是设计一个结构体这个思路比较好

#include <bits/stdc++.h>
using namespace std;
struct node {
    int x, y, step, count;
    node(int x_, int y_, int s_,
         int c_) : x(x_), y(y_), step(s_), count(c_) {}
};
vector<vector<int>> dir = {{1, -1, 0, 0}, {0, 0, 1, -1}};
bool check(vector<vector<bool>>& vis, int x, int y) {
    int n = vis.size(), m = vis[0].size();
    if(x >= 0 && x < n && y >= 0 &&
       y < m && !vis[x][y]) return 1;
    return 0;
}
int main() {
    int m, n;
    int sx, sy, ex,ey, ans = 0;
    scanf("%d%d", &n, &m);
    vector<string> grid(n);
    vector<vector<bool>> vis(n, vector<bool>(m, 0));
    for(int i = 0; i < n; ++i) {
        cin >> grid[i];
        int y;
        if((y = grid[i].find('S')) != -1) { sx = i; sy = y; }
        if((y = grid[i].find('E')) != -1) { ex = i; ey = y; }
    }
    queue<node*> q;
    q.push(new node(sx, sy, 0, 5));
    vis[sx][sy] = 1;
    bool flag = 0;
    while(q.size()) {
        node* top = q.front();
        q.pop();
        if(grid[top->x][top->y] == 'E') {
            printf("%d\n", top->step);
            flag = 1;
            break;
        }
        int xx, yy;
        for(int i = 0; i < 4; ++i) {
            xx = top->x + dir[0][i]; yy = top->y + dir[1][i];
            if(check(vis, xx, yy) && grid[xx][yy] != '#') {
                vis[xx][yy] = 1;
                q.push(new node(xx, yy, top->step + 1, top->count));
            }
        }
        xx = n - 1 - top->x; yy = m - 1 - top->y;
        if(top->count > 0 && check(vis, xx, yy) && grid[xx][yy] != '#') {
            vis[xx][yy] = 1;
            q.push(new node(xx, yy, top->step + 1, top->count - 1));
        }
        delete top;
    }
    if(!flag) printf("%d\n", -1);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值