跳到正文

闲话

每日一水

codm9478约 6 分钟
原文
文章信息与版本

文章信息

收录
2026年7月3日
更新
2026年7月3日
篇幅
约 6 分钟

版本

  1. v1当前

这是个 死人 私人题目的题解,编号U696377。

这作者纯乐子。记得多看看,有一些透明超链接,点进去的帖子也有。 这道题是三维数组,还有白名单逻辑。

以下为AC代码,

C++
#include <iostream>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <algorithm>

using namespace std;

// 定义最大范围
const int MAX_N = 25;
const int MAX_M = 25;
const int MAX_R = 405; 

// 全局 visited 数组,防止栈溢出
bool visited[MAX_N][MAX_M][MAX_R];

struct State {
    int x, y, urine, steps;
};

int n, m, sx, sy, R;
vector<string> grid;

// 方向数组:上、下、左、右
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};

// 判断字符是否可通行
// 根据提示:只有明确指定的字符(. W H)是可走的,其他字符(包括#和未知字符)不可走
bool isWalkable(char c) {
    return (c == '.' || c == 'W' || c == 'H');
}

int bfs() {
    // 清空 visited 数组
    memset(visited, false, sizeof(visited));

    // 特判:如果起点就是家,直接返回0
    if (grid[sx][sy] == 'H') {
        return 0;
    }

    // 检查起点是否合法
    if (!isWalkable(grid[sx][sy])) {
        return -1;
    }

    queue<State> q;
    
    // 初始状态:起点,尿意0,步数0
    q.push({sx, sy, 0, 0});
    
    visited[sx][sy] = true;
    
    while (!q.empty()) {
        State curr = q.front();
        q.pop();
        
        for (int i = 0; i < 4; ++i) {
            int nx = curr.x + dx[i];
            int ny = curr.y + dy[i];
            
            // 1. 边界检查
            if (nx < 0 || nx >= n || ny < 0 || ny >= m) {
                continue;
            }
            
            char nextChar = grid[nx][ny];

            // 2. 可通行性检查(白名单机制)
            if (!isWalkable(nextChar)) {
                continue;
            }
            
            // 3. 计算移动一步后的尿意
            int next_urine = curr.urine + 1;
            
            // 4. 严格死亡判断:尿意 >= R 则憋死
            if (next_urine >= R) {
                continue;
            }
            
            int final_urine = next_urine;
            
            // 5. 厕所机制:如果格子是 W,尿意清零
            if (nextChar == 'W') {
                final_urine = 0;
            }
            
            // 6. 终点判断:如果格子是 H,找到答案
            if (nextChar == 'H') {
                return curr.steps + 1;
            }
            
            // 7. 判重并入队
            if (!visited[nx][ny][final_urine]) {
                visited[nx][ny][final_urine] = true;
                q.push({nx, ny, final_urine, curr.steps + 1});
            }
        }
    }
    
    // 无法到达
    return -1;
}

int main() {
    // 优化 IO
    ios::sync_with_stdio(false);
    cin.tie(NULL);

    // 读取输入
    if (!(cin >> n >> m >> sx >> sy)) {
        return 0;
    }
    
    // 转换为 0-based 索引
    sx--; 
    sy--;
    
    grid.resize(n);
    for (int i = 0; i < n; ++i) {
        cin >> grid[i];
    }
    
    cin >> R;
    
    // 执行 BFS
    int result = bfs();
    
    // 输出结果
    if (result == -1) {
        cout << "No" << endl;
    } else {
        cout << result << endl;
    }
    
    return 0;
}
原文