直接上代码,痛快点。
package algorithm;
import junit.framework.TestCase;
/**
* Created by Rocky on 14-3-31.
* 下午7:59
*/
public class MyMaze extends TestCase {
/**
* @param maze 0表示可走,1表示不可走,2表示这步已走
* @param startI 入口横坐标
* @param startJ 入口竖坐标
* @param endI 出口横坐标
* @param endJ 出口竖坐标
*/
public void resolveMaze(int[][] maze, int startI, int startJ, int endI, int endJ) {
maze[startI][startJ] = 2;
System.out.println("*************走一步***************");
printMaze(maze);
if (startI == endI && startJ == endJ) {
System.out.println("********************成功*******************");
printMaze(maze);
} else {
/*向右*/
if(startJ + 1 < maze[startI].length){
if(maze[startI][startJ+1]==0 ){
resolveMaze(maze, startI, startJ+1, endI, endJ);
}
}
/*向下*/
if(startI + 1 < maze.length){
if(maze[startI+1][startJ]==0 ){
resolveMaze(maze, startI+1, startJ, endI, endJ);
}
}
/*向上*/
if(startI -1 >= 0){
if(maze[startI-1][startJ]==0 ){
resolveMaze(maze, startI-1, startJ, endI, endJ);
}
}
/*向左*/
if(startJ- 1 >=0){
if(maze[startI][startJ-1]==0 ){
resolveMaze(maze, startI, startJ-1, endI, endJ);
}
}
}
if (maze[startI][startJ] != 0) {
maze[startI][startJ] = 0;
}
System.out.println("*************退一步***************");
printMaze(maze);
}
private void printMaze(int[][] maze) {
for (int i = 0; i < maze.length; i++) {
for (int j = 0; j < maze[i].length; j++) {
if (maze[i][j] == 2) {
System.out.print("*\t");
} else {
System.out.print(maze[i][j] + "\t");
}
}
System.out.println();
}
}
public void test() {
int maze[][] = {
{0, 0, 3, 3, 3, 3, 3, 3, 3},
{3, 0, 0, 0, 0, 0, 0, 0, 3},
{3, 0, 3, 3, 0, 3, 3, 0, 3},
{3, 0, 3, 0, 0, 3, 0, 0, 3},
{3, 0, 3, 0, 3, 0, 3, 0, 3},
{3, 0, 0, 0, 0, 0, 3, 0, 3},
{3, 3, 0, 3, 3, 0, 3, 3, 3},
{3, 0, 0, 0, 0, 0, 0, 0, 0},
{3, 3, 3, 3, 3, 3, 3, 3, 0}};
resolveMaze(maze,0,0,8,8);
}
}
运行结果: