0
/*
 * main.c
 *
 *  Created on: Nov 30, 2012
 *      Author: mfb
 *
 *      Example input:
 *      5 5 2 2 0 0
 *  y0  . . . . .
 *  y1  a a a a .
 *  y2  . . . a .
 *  y3  . a a a .
 *  y4  . . . . .
 *
 *  x>  0 1 2 3 4
 *      I don't know why when I enter these to the program it comes to 4,4 and stops.
 */

#include <stdio.h>
int spx, spy, fx, fy, xsize, ysize;

char *inmap, *check;

int input(void) {
    scanf(" %d %d %d %d %d %d", &xsize, &ysize, &fx, &fy, &spx, &spy);
    inmap = (char *) malloc(xsize * ysize * sizeof(char));
    check = (char *) malloc(xsize * ysize * sizeof(char));

    int y;
    for (y = 0; y < xsize * ysize; y++)
        *(check + y) = 0;

    char o;
    for (y = 0; y < ysize * xsize; y++) {
        scanf(" %c", &o);
        if (o == '.')
            *(inmap + y) = 1;
        else
            *(inmap + y) = 0;
    }
    return 0;
}

int itaw(char *map, int fpx, int fpy) {
    if (*(check + fpy * xsize + fpx) == 1)
        return 0;
    else
        *(check + fpy * xsize + fpx) = 1;

    if (fpx >= xsize || fpy >= ysize || fpx < 0 || fpy < 0)
        return 0;

    if (*(map + fpy * xsize + fpx) == 0 || *(map + spy * xsize + spx) == 0)
        return 0;

    printf("(%d,%d)\n", fpx, fpy);
    if (fpx == spx && fpy == spy)
        return 1;

    return (itaw(map, fpx - 1, fpy) || itaw(map, fpx, fpy - 1)
            || itaw(map, fpx + 1, fpy) || itaw(map, fpx, fpy + 1));
}

int main(void) {
    input();
    int result = itaw(inmap, fx, fy);
    printf("%d\n", result);
    return 0;
}

上面是一个在两点之间找到路的程序。'。' 表示方式,所有其他字符表示墙壁。它大部分都有效,但是当我输入上面写的内容时,它返回 0。

4

1 回答 1

5

问题是您在访问变量之前没有进行边界检查。在访问之前,您必须确保它们大于 0 且小于 max check。我认为这是正确的版本:

int itaw(char *map, int fpx, int fpy) {
    if (fpx >= xsize || fpy >= ysize || fpx < 0 || fpy < 0)
        return 0;
    if (*(check + fpy * xsize + fpx) == 1)
        return 0;
    else
        *(check + fpy * xsize + fpx) = 1;
于 2012-11-30T17:08:35.597 回答