文章

1

粉丝

6

获赞

10

访问

650

头像
迷宫 题解:我自己跑都没啥问题,为什么在这就runtime error?
P1563 天津大学/南开大学机试题
发布于2025年2月27日 00:03
阅读数 650

#include<stdio.h>
typedef struct
{
    int x;
    int y;
    int step;
}node;
typedef struct
{
    node data[10000];
    int f, r;
}Queue;
void Init(Queue *Q)
{
    Q->f = Q->r = 0;
}
int isempty(Queue Q)
{
    return Q.f == Q.r;
}
void EnQueue(Queue *Q, node e)
{
    Q->data[Q->r++] = e;
}
void DeQueue(Queue *Q, node *e)
{
    *e = Q->data[Q->f++];
}
int dx[4] = { 0,1,0,-1 };//右下左上
int dy[4] = { 1,0,-1,0 };
int main()
{
    int h, w;
    int ans;
    char a[100][100];
    Queue Q;
    while (scanf("%d%d", &h, &w) != EOF)
    {
        if (h == 0 && w == 0)
            break;
     ...

登录查看完整内容


登录后发布评论

2 条评论
快乐小土狗
2025年2月27日 02:30

这段代码出现运行时错误(Runtime Error)的原因主要有以下几点:

1. 迷宫数组越界访问
代码中定义的迷宫数组为 char a[100][100],而在读取输入时循环变量 i 和 j 的范围是从 1 到 h 和 w。如果输入的 h 或 w 超过 100,会导致数组越界访问。例如,当 h=101 时,访问 a[101][j] 会越界。

2. 未检查移动后的坐标合法性
在四个方向的移动中,未检查新坐标 tx 和 ty 是否在迷宫范围内。当移动到迷宫外时,访问 a[tx][ty] 会导致越界。

3. 队列容量不足
队列 data 的大小为 10000。当迷宫较大(例如 h=100, w=100)时,最多需要存储 10000 个节点,此时队列指针 r 会增加到 10000,导致越界访问 data[10000](有效索引为 0~9999)。

赞(0)

XJL453 : 回复 快乐小土狗: 谢谢老哥,明白了

2025年2月27日 13:15