37 条题解

  • 0
    @ 2025-7-21 15:42:21
    #include <iostream>
    #include <queue>
    using namespace std;
    
    // 定义方向数组,表示马可以走的8个方向
    const int dx[] = {-2, -1, 1, 2, 2, 1, -1, -2};
    const int dy[] = {1, 2, 2, 1, -1, -2, -2, -1};
    
    struct Point {
        int x, y, steps;
        Point(int _x, int _y, int _s) : x(_x), y(_y), steps(_s) {}
    };
    
    int main() {
        int rows, cols;
        cin >> cols >> rows; // 注意题目先给列数再给行数
        
        char map[155][155];
        bool visited[155][155] = {false};
        queue<Point> q;
        int start_x, start_y, end_x, end_y;
        
        // 读取地图
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                cin >> map[i][j];
                if (map[i][j] == 'K') {
                    start_x = i;
                    start_y = j;
                } else if (map[i][j] == 'H') {
                    end_x = i;
                    end_y = j;
                }
            }
        }
        
        // BFS开始
        q.push(Point(start_x, start_y, 0));
        visited[start_x][start_y] = true;
        
        while (!q.empty()) {
            Point current = q.front();
            q.pop();
            
            // 如果到达终点
            if (current.x == end_x && current.y == end_y) {
                cout << current.steps << endl;
                return 0;
            }
            
            // 尝试8个方向
            for (int i = 0; i < 8; i++) {
                int nx = current.x + dx[i];
                int ny = current.y + dy[i];
                
                // 检查边界
                if (nx < 0 || nx >= rows || ny < 0 || ny >= cols) continue;
                
                // 检查是否已访问或是否是障碍物
                if (visited[nx][ny] || map[nx][ny] == '*') continue;
                
                // 标记为已访问并加入队列
                visited[nx][ny] = true;
                q.push(Point(nx, ny, current.steps + 1));
            }
        }
        
        // 如果无法到达
        cout << "-1" << endl;
        return 0;
    }
    
    

    信息

    ID
    1
    时间
    1000ms
    内存
    128MiB
    难度
    1
    标签
    递交数
    4607
    已通过
    1304
    上传者