跳到正文

休闲·娱乐

P8673

Gua20131127约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年7月15日
收录
2025年12月12日
更新
2026年11月16日
篇幅
约 3 分钟
题目
P8673

版本

  1. v1当前
C++
#include<bits/stdc++.h>
using namespace std;
struct node{
    int x , y , val , step;
};
const int N = 1010;
int n , k;
int vis[N][N];
char a[N][N];
int d[4][2] = {{-1 , 0} , {0 , -1} , {0 , 1} , {1 , 0}};
int bfs(int x , int y){
    for(int i = 1;i <= n;i ++){
        for(int j = 1;j <= n;j ++){
            vis[i][j] = -1;
        }
    }
    queue<node>q;
    vis[1][1] = 0;
    q.push({1 , 1 , 0 , 0});
    while(q.size()){
        node t = q.front();
        q.pop();
        if(t.x == n && t.y == n){
            return t.step;
        }
        for(int i = 0;i < 4;i ++){
            int px = t.x + d[i][0];
            int py = t.y + d[i][1];
            if(a[px][py] == 'X' && t.val == 0){
                continue;
            }
            if(px < 1 || px > n || py < 1 || py > n){
                continue;
            }
            if(a[px][py] == '#'){
                continue;
            }
            int val = max(0 , t.val - 1);
            if(val <= vis[px][py]){
                continue;
            }
            if(a[px][py] == '%'){
                val = k;
            }
            vis[px][py] = val;
            q.push({px , py , val , t.step + 1});
        }
    }
    return -1;
}
int main(){
    cin >> n >> k;
    for(int i = 1;i <= n;i ++){
        for(int j = 1;j <= n;j ++){
            cin >> a[i][j];
        }
    }
    cout << bfs(1 , 1);
    return 0;
}
原文