public class Maze3D {
private final int TRIED = 3;
private final int PATH = 7;
private final int BLOCKED = 0;
private final int OPEN = 1;
private int[][][] grid = {
{ { 1, 1, 1, 0, 0 }, { 0, 0, 1, 0, 0 }, { 0, 1, 1, 1, 0 },
{ 0, 1, 0, 0, 0 }, { 0, 1, 1, 0, 0 } },
{ { 0, 1, 0, 0, 0 }, { 0, 1, 1, 0, 0 }, { 1, 1, 1, 1, 0 },
{ 1, 1, 0, 1, 1 }, { 1, 0, 0, 0, 1 } },
{ { 1, 1, 1, 0, 0 }, { 0, 0, 1, 0, 0 }, { 0, 0, 0, 1, 0 },
{ 0, 1, 1, 1, 1 }, { 0, 1, 0, 0, 0 } },
{ { 0, 0, 0, 0, 0 }, { 0, 1, 1, 0, 0 }, { 0, 1, 0, 1, 1 },
{ 0, 0, 0, 0, 1 }, { 0, 1, 1, 0, 0 } },
{ { 0, 0, 1, 1, 0 }, { 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 1 }, { 0, 0, 1, 0, 1 } }
public boolean traverse(int row, int column, int depth) {
boolean done = false;
if(valid(row,column,depth))
{
grid[row][column][depth]= TRIED;
if(row==grid.length-1&&column==grid[0].length-1&&depth==grid[0][0].length-1)
done=true;
else
{
done=traverse(row+1,column,depth);
if(!done)
done=traverse(row,column+1,depth);
if(!done)
done=traverse(row,column,depth+1);
if(!done)
done=traverse(row-1,column,depth);
if(!done)
done=traverse(row,column-1,depth);
if(!done)
done=traverse(row,column,depth-1);
}
if (done)
grid[row][column][depth]=PATH;
}
return done;
}
} private boolean isValid (int row,int column,int depth)
{
boolean result= false;
if(row>=0 && row<grid.length && column>=0 && column<grid[row].length && depth>=0 && depth<grid[column].length)
if (grid[row][column][depth]==1)
result = true;
return result;
}
// Print path in sequence of coordinates (row, col, depth)
public void printPath() {
int row = 0, col = 0, depth = 0;
while (row < grid.length && col < grid[0].length
&& depth < grid[0][0].length) {
System.out.println("[" + row + ", " + col + ", " + depth + "]");
// this will temporarily marks visited path
grid[row][col][depth] *= -1;
if (isPath(row, col, depth + 1))
depth++;
else if (isPath(row, col, depth - 1))
depth--;
else if (isPath(row, col + 1, depth))
col++;
else if (isPath(row, col - 1, depth))
col--;
else if (isPath(row + 1, col, depth))
row++;
else if (isPath(row - 1, col, depth))
row--;
else {
break;
}
}
for (row = 0; row < grid.length; row++)
for (col = 0; col < grid[row].length; col++)
for (depth = 0; depth < grid[row][col].length; depth++)
if (grid[row][col][depth] < 0)
grid[row][col][depth] *= -1;
}
This post has been edited by vict4321: 13 November 2008 - 12:35 AM

New Topic/Question
Reply




MultiQuote


|