📄 mazemodel2.java
字号:
import java.util.*;
public class MazeModel extends Object {
static private int NORTH=0,SOUTH=1,EAST=2,WEST=3,FAILED=4;
static private int ROW_MAX=15, COL_MAX=30;
private char[][] maze;
private int startRow, startCol;
private MazeView view;
private class ChoicePoint extends Object {
private int row, col, direction;
private ChoicePoint(int row, int col, int direction) {// constructor
this.row = row; this.col = col; this.direction = direction; }
public int getDirection() { return direction; }
public int getRow() { return row; }
public int getCol() { return col; }
}
public MazeModel(MazeView mv) { // constructor
view = mv;
maze = new char[ROW_MAX][COL_MAX];
initMaze();
}
public void initMaze() {
for(int row=0; row < ROW_MAX; row++)
for(int col=0; col < COL_MAX; col++)
maze[row][col] = '*';
}
private void findStartPos() {
for(int row=0; row < ROW_MAX; row++)
for(int col=0; col < COL_MAX; col++)
if (maze[row][col] == 'P')
{ startRow = row; startCol = col; return; }
}
public boolean solveMaze(){
findStartPos();
maze[startRow][startCol] = '*';
boolean solved = getOut();
maze[startRow][startCol] = 'P';
view.printMaze();
return solved;
}
public boolean getOut(){
Stack s = new Stack();
ChoicePoint c;
int currDir = -1;
int currRow, currCol, newRow, newCol;
c = new ChoicePoint(startRow, startCol, currDir);
s.push(c);
while(s.size() > 0) { // while1
//退栈,将退出的点作为当前点
//while(如当前点的方向不是FAILED)
{
沿当前方向前进一格;
if(当前元素值为'T') return true;;
else
if (当前元素值为空) {
将当前元素值置为'。';
将当前点压入堆栈;
将当前方向置为NORTH;
else
将当前方向置为下一方向;
}
}
return false;
}
// the following methods are called from MazeView.java
public void setMaze(String mazeStr) {
for(int row=0; row < ROW_MAX; row++)
{
int strPos = row * COL_MAX + row;
for( int col = 0; col < COL_MAX; col++)
{
maze[row][col] = mazeStr.charAt(strPos);
strPos++;
}
strPos++;
}
}
public String getMaze() {
String str = "";
for(int row=0; row < ROW_MAX; row++)
{
for( int col = 0; col < COL_MAX; col++)
str = str + maze[row][col];
str = str + "\n";
}
return str;
}
public String getResult() {
String str = "";
for(int row=0; row < ROW_MAX; row++)
{
for( int col = 0; col < COL_MAX; col++) {
if (maze[row][col]=='A')
maze[row][col]=' ';
str = str + maze[row][col];
}
str = str + "\n";
}
return str;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -