Jump to content

Maze Program Stack Overflow?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
javanewb19

javanewb19

    Newbie

  • Members
  • Pip
  • 1 posts
I was hoping someone could give me some hints or suggestions with this program. It's been driving me nuts. Before, it would move in squares that were blocked at times (using the debugger I saw this) and now it won't run at all and says there's a stack overflow. I'm sure its some detail I'm missing etc. All it has to do is check and see if tehre is an exit to the maze using recursion. Anyway, any help would be greatly appreciated!

Thanks.



public class Maze
{
private char[][] m;

public Maze(char [][]l)
{
m = l;
}

public boolean escape(int r, int c)
{

	boolean done = false;

if (valid(r,c))
{
	char x;
	x = m[r][c];
	if (r == 0 && c == 1)
		done = true;
	else 
	{
		done = escape (r+1, c);
		
		if (!done && (x != '*' || x == '0'))
			done = escape(r, c+1);
			m[r][c] = '0';
			
		if(!done && (x != '*' || x == '0'))
			done = escape(r-1, c);
			m[r][c] = '0';
		if(!done && (x != '*' || x == '0'))
			done = escape(r, c-1);
			m[r][c] = '0';
	}
	
	if(done)
		done = true;
}
return done;
}

private boolean valid(int r, int c)
{
	boolean result = false;
	
if (r >= 0 && r < m.length-1 && c >= 0 && c < m[r].length-1)
		result = true;
		return result;


}

}

public class MazeTester
{
public static void main(String args[])
{ 
	

char[][] m =
{
{'*', ' ', '*', '*', '*', '*', '*', '*', '*'},
{'*', ' ', ' ', ' ', ' ', ' ', '*', ' ', '*'},
{'*', ' ', '*', '*', '*', '*', '*', ' ', '*'},
{'*', ' ', '*', ' ', '*', ' ', ' ', ' ', '*'},
{'*', ' ', '*', ' ', '*', '*', '*', ' ', '*'},
{'*', ' ', ' ', ' ', '*', ' ', ' ', ' ', '*'},
{'*', '*', '*', ' ', '*', '*', '*', '*', '*'},
{'*', ' ', ' ', ' ', ' ', ' ', '*', ' ', '*'},
{'*', '*', '*', '*', '*', '*', '*', ' ', '*'}
};
Maze maze = new Maze(m);
System.out.println(maze.escape(4,3));
System.out.println("Expected: true");
}
}

Edited by WingedPanther, 09 December 2008 - 08:36 AM.
add code tags (the # button)


#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
I see a couple of things that could be wrong, but with no comments on your logic, I'm not sure:
1) In your if statements when checking !done && (x != '*' || x == '0'), you don't wrap the following two statements in {}. That doesn't look right to me.
2) (x != '*' || x == '0') is equivalent to x != '*', why the second half?
3) shouldn't you be testing the potential escape route for a '*' rather than the current position?
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog