Question

i am trying to print a solution path in a maze.Every cell has a parent from where we go to that cell.I am printing the path with the following code.

                do{
                System.out.print("The parent of "+index1+","+index2+"=");
                System.out.println(theParents[index1][index2][0]+","+theParents[index1][index2][1]);
                index1=theParents[index1][index2][0];
                index2=theParents[index1][index2][1];
                }while(!(index1==2 && index2==1));

the problem is that is skips some cells.I couldn't figure out why?

The parent of 7,7=6,7

The parent of 6,7=5,7

The parent of 5,7=4,7

The parent of 4,7=3,7

The parent of 3,7=2,7

The parent of 2,7=1,7 // as you see we should now print 1,7 but it skips 1,7 and goto 1,6

The parent of 1,6=1,5

The parent of 1,5=2,5 // it skips 2,5 and go to 2,3 directly

The parent of 2,4=2,3

The parent of 2,3=1,3

The parent of 1,2=1,1

The parent of 1,1=0,1

The parent of 0,0=1,0

The parent of 1,0=2,0

What is wrong with the code?

Was it helpful?

Solution

index1=theParents[index1][index2][0];
index2=theParents[index1][index2][1]; // the index1 here is already reassigned!

You've already reassigned index1 when you go to use it in the assignment of index2.

You need something like

int newindex1 = theParents[index1][index2][0];
int newindex2 = theParents[index1][index2][1];

index1 = newindex1;
index2 = newindex2;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top