【发布时间】:2015-03-23 09:51:00
【问题描述】:
我正在尝试使用递归来遍历迷宫。给了我模板,只需要输入穿越迷宫的过程;除了在此之后插入的代码之外,我不允许以任何方式更改代码:
public boolean mazeTraversal (char maze2[][], int x, int y)
我一直很难解决这个问题,不知道我错过了什么。在 Java 和一般编程方面,我仍然是超级菜鸟。任何提示将不胜感激。
// Exercise 18.20 Solution: Maze.java
//Program traverses a maze.
import java.util.Scanner;
package maze;
public class Maze {
public static void main( String args[] )
{
}
/**
* @param args the command line arguments
*/
static final int DOWN = 0;
static final int RIGHT = 1;
static final int UP = 2;
static final int LEFT = 3;
static final int X_START = 2;
static final int Y_START = 0;
static final int move = 0;
static char maze [][] =
{ { '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#' },
{ '#', '.', '.', '.', '#', '.', '.', '.', '.', '.', '.', '#' },
{ 'S', '.', '#', '.', '#', '.', '#', '#', '#', '#', '.', '#' },
{ '#', '#', '#', '.', '#', '.', '.', '.', '.', '#', '.', '#' },
{ '#', '.', '.', '.', '.', '#', '#', '#', '.', '#', '.', 'F' },
{ '#', '#', '#', '#', '.', '#', '.', '#', '.', '#', '.', '#' },
{ '#', '.', '.', '#', '.', '#', '.', '#', '.', '#', '.', '#' },
{ '#', '#', '.', '#', '.', '#', '.', '#', '.', '#', '.', '#' },
{ '#', '.', '.', '.', '.', '.', '.', '.', '.', '#', '.', '#' },
{ '#', '#', '#', '#', '#', '#', '.', '#', '#', '#', '.', '#' },
{ '#', '.', '.', '.', '.', '.', '.', '#', '.', '.', '.', '#' },
{ '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#' } };
static Scanner scanner = new Scanner (System.in);
//method calls mazeTraversal with correct starting point and direction
public void traverse ()
{
boolean result = mazeTraversal (maze, X_START, Y_START);
if (!result)
System.out.println ("Maze has no solution.");
} //end method traverse
//traverse maze recursively
public boolean mazeTraversal (char maze2[][], int x, int y)
{
// TO BE COMPLETED
//check for boundaries
if (x < 0 || y < 0 || x >= maze.length || y >= maze[0].length)
return false;
//base case - did I reach finish?
if(maze [x][y] == 'F')
return true;
//check if Valid point
if (maze [x][y] != '.' || maze[x][y] != 'S')
// hit a wall, not valid
return false;
//must be on a path, may be the right path
//breadcrumb
maze [x][y] = '.';
//up
if (mazeTraversal (x+1,y))
{
maze [x][y]= '#';
return true;
}
if (mazeTraversal (x,y+1))
{
maze [x][y] = '#';
return true;
}
// can't go any further
return false;
}
}
//draw maze
public void printMaze()
{
// for each space in maze
for ( int row = 0; row < maze.length; row++)
{
for (int column = 0; column < maze [row].length; column++)
{
if (maze [x][y] == '0')
System.out.print (".");
else
System.out.print (" " + maze [x][y]);
}
System.out.println();
}
System.out.println();
}
}
【问题讨论】:
-
查看stackoverflow.com/questions/22239871/… 以获得一些提示 - 看起来非常接近您的开始。
-
你会说我现在走在正确的轨道上吗?
-
第一点是你的代码没有格式化,实际上并没有编译。如果你解决了这个问题,人们就会更容易看到你的问题并给你一些帮助。有关您问题的实际答案,请参见下文。
标签: java recursion traversal maze