一、题目
题目很简单,在迷宫内,给定起始点和终点,根据一定的行走策略,使用递归操作,找出一条可以行走的路径。
二、源代码
package recursion;
import java.util.Stack;
public class Maze {
public static void main(String[] args) {
int width = 8, height = 8;
int startX = 1, startY = 1,endX = 6, endY = 6; //按照数组索引来书写
// 初始化迷宫
String[][] mazeMap = makeMaze(width,height);
drawMaze(mazeMap,width,height);
// 寻找迷宫的路径,只有一条,并不是最短路径
findPath(mazeMap,startX,startY,endX,endY, startX, startY);
drawMaze(mazeMap,width,height);
}
/*
* 1. 制作迷宫地图
*/
public static String[][] makeMaze(int width,int height) {
String[][] mazeMap = new String[width][height];
String barrier = "×"; //障碍物
String cell = "o"; //格子
for(int i=0;i<width;i++) {
for(int j=0;j<height;j++) {
mazeMap[i][j] = cell;
}
}
for(int i=0;i<width;i++) {
mazeMap[i][0] = barrier;
mazeMap[i][height-1] = barrier;
}
for(int j=0;j<height;j++) {
mazeMap[0][j] = barrier;
mazeMap[width-1][j] = barrier;
}
mazeMap[3][1] = barrier;
mazeMap[3][2] = barrier;
// mazeMap[1][3] = barrier;
// mazeMap[2][3] = barrier;
return mazeMap;
}
/*
* 2. 制定递归策略,走迷宫. ">"表示要走的路径
*/
public static Boolean findPath(String[][] maze, int startX, int startY,int endX, int endY,int x,int y){
String cell = "o", //格子,还未走过的路径
pathCell = "※"; //可以走的路径
int rowLength = maze.length,
colLength = maze[0].length;
if((startX>0 && startX<rowLength-1) && (startY>0 && startY<colLength-1) &&
(endX>0 && endX<rowLength-1) && (endY>0 && endY<colLength-1)) {
// 找到了终点坐标
if(maze[endX][endY].equals(pathCell)) {
return true;
}else {
// 寻找路径,策略是往"上 右 下 左"顺序走
// 只有该格子是空白的格子才会有if,否则只能走else
if(maze[x][y].equals(cell)) {
maze[x][y] = pathCell;
if(findPath(maze, startX, startY, endX, endY, x-1,y)) {
return true;
}else if(findPath(maze, startX, startY, endX, endY, x,y+1)) {
return true;
}else if(findPath(maze, startX, startY, endX, endY, x+1,y)) {
return true;
}else if(findPath(maze, startX, startY, endX, endY, x,y-1)) {
return true;
}else {
// 回溯回去,证明此路不通
maze[x][y] = "?";
drawMaze(maze,rowLength,rowLength);
return false;
}
}else {
return false;
}
}
}else {
System.out.println("\n坐标设定有误,应该在围墙之内\n");
return false;
}
}
/*
* 3.绘制迷宫地图
*/
public static void drawMaze(String[][] mazeMap, int width, int height) {
System.out.print("\n迷宫:\n");
for(int i=0;i<width;i++) {
for(int j=0;j<height;j++) {
System.out.print(mazeMap[i][j] + " ");
}
System.out.println();
}
}
}
三、结果
符号"x"表示围墙,“o"表示可以走的格子。
行走的策略是"上 右 下 左”,所以会得到下面带"※“的路径。
如果我们转换行走策略,变成"下 右 上 左”,又会得到不同的路径,如下。
所以,如果要求最短的行走路径,只需要找出在不同行走策略(4*3*2*1种可能)下带"※"格子数最少的路径即可。