I have a piece of code:
private void colorize(int color, int x, int y) {
visited[x][y] = true;
if (x + 1 < d)
if (board[x + 1][y] == board[x][y] && visited[x + 1][y] == false)
colorize(color, x + 1, y);
if (x - 1 >= 0)
if (board[x - 1][y] == board[x][y] && visited[x - 1][y] == false)
colorize(color, x - 1, y);
if (y + 1 < d)
if (board[x][y + 1] == board[x][y] && visited[x][y + 1] == false)
colorize(color, x, y + 1);
if (y - 1 >= 0)
if (board[x][y - 1] == board[x][y] && visited[x][y - 1] == false)
colorize(color, x, y - 1);
board[x][y] = color;
}
I call it: colorize(int random, int 0, int 0). This gives me stackoverflow even for a small table (20×20). How can I do this without recursion?
The code as given seems fine.
There is a question as to what
dis, but I’m assuming that it is correctly the width of a square grid.It’s possible that you have a problem in whatever code calls this, but the code you have given us should not have a stack overflow.
Building off of Måns Rolandi Danielsson’s answer, here is one that doesn’t use the explicit stack, but builds one on the heap. My java is extremely rusty, but this should work. If anyone has fixes for this code, feel free to fix it.
Instead of getting a stack overflow, at large table sizes I get a
java.lang.OutOfMemoryError: Java heap spaceerror instead. You could probably use a set or some other data structure (rather than a linked list) to optimize memory usage.