【发布时间】:2017-07-16 20:12:38
【问题描述】:
我需要使用 2D 数组和堆栈构建一个迷宫。数组大小是固定的。起点是(0,0)。数组应该从文件中读取,但在这个例子中,我假设值只是为了让事情更清楚。
我似乎找不到合适的算法让我遍历二维数组并将路径保存到堆栈。如果我被困在当前行,这会让我回到上排。 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 中的相同,并且包含相同的方法(pop、push)
【问题讨论】:
-
我需要一种算法来解决迷宫问题。这还不够。如果我在我所在的行被 1 阻止,我需要知道什么时候回去。
-
如果你在现实生活中的迷宫里,你会怎么做?
-
“我需要一个算法...”不是一个问题,而是一个故事。你有什么问题?
标签: java arrays multidimensional-array stack maze