简体   繁体   中英

Solving a maze in 2d array

I had referred to many articles and questions that answered how to solve a maze effectively but here I want to confirm what's going wrong in my code. Consider the maze:

2 1 0 0 3
0 1 0 1 1
0 1 0 0 1
0 1 1 0 0
0 0 0 0 0

where the 1's represent the walls and 0's represent the path.(source is 2 and destination is 3). I have to output whether there is a path or not.

int y=0;
        while(y==0)
        {
            robo1(n,m,maze);//this function adds 2 to any '0'/'3' in (i,j+1),(i+1,j),(i-1,j),(i,j-1) (if exists),where (i,j) is 2
            robo2(n,m,k2,maze);//this function adds 3 to any '0'/'2' in (i,j+1),(i+1,j),(i-1,j),(i,j-1) (if exists), where (i,j) is 3
            if(find5(n,m,maze)==1)//this function returns 1 if there is '5' in the maze
                y++;
            if(find0(n,m,maze)==0)//this function returns 0 if there are no '0' in the maze
                break;
        }
        if(find0(n,m,maze)==0 && y==0)
            printf("-1\n");//no path
        else
            printf("1\n");//there is a path

My idea is that if after any number of loops a five is found in the maze, then it would mean there is a path. But while implementing this function in code I get wrong answers and sometimes run-time errors. Is there any flaw in the above logic?

The general idea should almost work, but of course everything is in the details.

One case in which your approach will not work even if implemented correctly is however this:

  2 1 0 0 0
  1 1 0 1 1 
  0 0 0 1 3

ie if both 2 and 3 are "closed" by walls but there are 0s in the room. Your loop will never end because despite having 0s around neither of the two robo function will change anything.

A simple solution is returning 0/1 from robos if they actually changed at least a value in the matrix and quitting when this doesn't happen.

Note that this is not a very efficient way of solving a maze (your code will keep checking the same cells over and over many times).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM