0
我需要使用二維數組和堆棧構建一個迷宮。數組大小是固定的。起點是(0,0)。數組應該從文件中讀取,但在這個例子中,我假定值只是爲了說清楚。使用二維數組和堆棧在java中構建迷宮
我似乎無法找到一個合適的算法,讓我通過二維數組並保存我的路徑到堆棧。如果我卡在當前行中,那會讓我回到上一行。 PS:1是牆壁,0是路徑。的問題,需要通過用戶的輸入陣列,但我爲了簡單
赫雷什提供的一個陣列:
0 1 0 0 0
0 1 0 0 0
0 0 0 0 0
1 1 1 0 0
0 1 0 0 0
我需要從位置(0,0)開始和出口應在最後行。如果我陷入困境,我需要走上另一條路;那是彈出堆棧。
這就是我想出了:
public class Maze {
Maze currentPos = new Maze();
int position = maze[0][0];
public Maze()
{
}
public Maze(Maze currentPos)
{
this.currentPos = currentPos;
position = maze[0][0];
}
Stack stack = new Stack();
public static int[][] maze = new int[][] {
{0,1,0,0,0},
{0,1,0,0,0},
{0,0,0,0,0},
{1,1,1,0,0},
{0,1,0,0,0}
};
public boolean UP (int i, int j)
{
if (maze [i-1][j] == 0)
return true;
return false;
}
public boolean DOWN (int i, int j)
{
if (maze [i+1][j] == 0)
return true;
return false;
}
public boolean RIGHT(int i,int j)
{
if (maze [i][j+1] == 0)
return true;
return false;
}
public boolean LEFT(int i,int j)
{
if (maze [i][j-1] == 0)
return true;
return false;
}
public boolean isExit (int i, int j)
{
if (j == 6)
return true;
return false;
}
public void setPosition(int i , int j)
{
position = maze[i][j];
}
public void solve()
{
for (int i=0; i<maze.length; i++)
{
for (int j=0; j<maze.length; j++)
{
while(! currentPos.isExit(i,j));
{
if (currentPos.DOWN(i,j)) stack.push(i+1,j);
if (currentPos.LEFT(i,j)) stack.push(i,j-1);
if (currentPos.RIGHT(i,j)) stack.push(i,i+1);
if (currentPos.UP(i,j)) stack.push(i-1,j);
}
}
}
}
}
類棧是一樣的一個在java.util.Stack中,並用同樣的方法包括:(彈出,推)
我需要一個算法,使我能夠解決迷宮。這一個是不夠的。我需要知道什麼時候回去,如果我在我所在的行中被阻擋了1。 – RADMRA
如果你在一個真實的迷宮中,你會怎麼做? –
「我需要一種算法......」不是一個問題,而是一個故事。你有什麼問題? – EJoshuaS