I am having trouble finishing this program. The assignment is to use recursion to find a path through a maze composed of X's and O's. The path one can go through is designated by the O's The maze is stored as a text file.

Here is a sample maze:

XOXXXXXX
XOXXXXXX
XOOOOXXX
XXXXOXXX
XXXXOOXX
XXXXXOXX    
XXXXXOOO
XXXXXXXO

And here is my attached code. I am attatching all of my code, but I would not like to be told exactly how to do it, I am here to learn :-).I do believe my problem is with not accounting for the same O i just looked for, but im not 100% sure. Thanks!!

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    int find_path(char maze[8][8], int coorx, int coory);

    int main(int argc, char *argv[])
    {
      char maze[8][8];
      int i=0,j=0;

      FILE *fp;
      fp = fopen(argv[1], "r");
      for(i=0;i<9;i++)
        for(j=0;j<9;j++)
          fscanf(fp,"%c",&maze[i][j]);
      fclose(fp);
      printf("%c", maze[2][3]);
      return 0;
    }

    int find_path(char maze[8][8], int coorx, int coory)
    {
      //if((maze[coorx][coory]!= 'O') && (coorx >=0) && (coorx < 8) && (coory >=0) &&
          //(coorx < 8)){
        if(find_path(maze, coorx + 1, coory) == 'O'){
          printf("(%d,%d)",coorx, coory);
        }
        else if(find_path(maze, coorx - 1, coory) == 'O'){
          printf("(%d,%d)",coorx, coory);
        } 
        else if(find_path(maze, coorx, coory + 1) == 'O'){
          printf("(%d,%d)",coorx, coory);
        }
        else if(find_path(maze, coorx, coory - 1) == 'O'){
          printf("(%d,%d)",coorx, coory);
        }

      return 0;
    }
有帮助吗?

解决方案 2

find_path doesn't have a clear base case, since the if at the beginning is commented out. The very first thing it does, is call itself again with cell to the right. And the first thing that call does, is call itself again, with the cell to the right of that. There's nothing to stop it from just falling right off the end of the array, at which point it's just dumb luck you haven't caused missiles to launch somewhere.

Even if that weren't the case, there's nothing keeping it from getting stuck between a cell with a wall to the right, and the cell just to the left of it. You try to go right, but can't, so you go left. Next step, you can go right again, so you do. Repeat for all eternity (or at least til you eat up your stack).

其他提示

You have this declaration

char maze[8][8];

And loop like this

for(i=0;i<9;i++)

That is, you loop from zero to eight (inclusive) which is nine indexes. For an array of only eight entries.

This means you will write out of bounds of the arrays, leading to undefined behavior.

Either change your loop condition, or increase your array sizes.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top