递归、回溯问题
HanoiTower问题
public class HanoiTower {
public static void main(String[] args) {
Test test = new Test();
test.move(3, 'A', 'B', 'C');
}
}
class Test {
public void move(int num, char A, char B, char C) {//起点,过度点,终点
if (num == 1) {
System.out.println(A + "->" + C);
} else {
move(num - 1, A, C, B);//将除了最下面的那一个以外的所有,从A移动到B借助C
System.out.println(A + "->" + C);//将最下面的那个移动C
move(num-1, B, A, C) ;//将这些从B移动到C借助A(放到最上面!)
}
}
}
小老鼠走迷宫问题
map:
public class MiGongGame {
public static void main(String[] args) {
int[][] map = new int[8][7];
for (int i = 0; i < 8; i++) {
map[i][0] = 1;
map[i][6] = 1;
}//将第一列和最后一列置为1
map[3][2] = 1;
map[3][1] = 1;
for (int i = 0; i < 7; i++) {
map[0][i] = 1;
map[7][i] = 1;
}//将第一行和最后一行置为1
/**
* 设置好了地图,接下来实例化一个对象然后调用方法进行找路!
*将map地方和初始化的坐标传进去,让程序运行,自己找路。
*/
Test test = new Test();
test.findway(map, 1, 1);
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
System.out.print(map[i][j]);
}
System.out.println();
}
}
}
/**
*游戏规则:0为目前这个位置能走,但不知道能不能走动(就是可以走,但是不知道路通不通)
* 1为障碍物,不能走
* 2为这条路是通路,可以走
* 3这条路走过了,是死路,不能走
*/
class Test {
public boolean findway(int[][] map, int i, int j) {
if (map[6][5] == 2) {
return true;//表示找到了!
} else {//说明还没有找到!
if (map[i][j] == 0) {//目前这个位置能走,但不知道能不能走动(就是可以走,但是不知道路通不通)
map[i][j] = 2;//假设这个位置可以走动
//下面使用找路策略
//先下 右 上 左
if (findway(map, i + 1, j)) {//控制程序向下走一步,看看能不能走,如果能就返回true,不然则走elseif语句
return true;
} else if (findway(map, i, j + 1)) {//控制程序向右走一步,看看能不能走,如果能就返回true,不然则走elseif语句
return true;
} else if (findway(map, i - 1, j)) {//控制程序向上走一步,看看能不能走,如果能就返回true,不然则走elseif语句
return true;
} else if (findway(map, i, j - 1)) {//控制程序向左走一步,看看能不能走,如果能就返回true,不然则走else语句
return true;
} else {//以上的情况都不满足,那么就说明这条路是堵住的!直接将这个点置为3,并回溯,(回溯就是返回上一步的意思,因为这个点是我们假定设置成2的,不一定能走的!)
map[i][j] = 3;
return false;
}
} else {
return false;//连0都不是 那么就是123,直接false:
}
}
}
}