汉诺塔
递归思想只考虑两种情况
- 只有一个圆盘, 只需将a上的圆盘移动到c盘即可,即a -> c
- 有多个圆盘时,将在a上的圆盘分为两部分,最下面的圆盘和上面的所有圆盘。想要将最下面的圆盘移动到c,则
- 将上面部分移动到b,期间借助c。即move(a, c, b)
- 将a上剩余的最下面的圆盘移动到c。a -> c
- 将处于b的“上面部分”移动到c,期间借助a。即move(b, a, c)
public class HanoiTower {
public static void main(String[] args) {
Tower tower = new Tower();
tower.move(5, 'A', 'B', 'C');
}
}
class Tower{
public void move(int num, char a, char b, char c){
if (num == 1){ //只有一个盘
System.out.println(a + " -> " + c);
}else{ //多个盘
//最后一个盘移到c,需要将其他的东西移到b
move(num - 1, a, c, b); //a移到b借助c
//将最后一个盘移到c
System.out.println(a + " -> " + c);//a到c
//将上面所说“其他的东西”从b移到c,需要借助a
move(num - 1, b, a , c);//b移到c借助a
}
}
}
迷宫
- 1代表障碍
- 0代表空白未探索
- 2代表路径
- 3代表探索过的路径但是行不通。
findWay()
- 如果走出迷宫的条件不满足,则持续走,直到找不到解(一开始四个方向都为false)
- 否则,如果这个位置没有探索过,先将其设置为2,然后依照下右上左的策略进行探索,若上下左右都探索过且行不通,则设置为3,引发回溯。
public class Puzzle {
public static void main(String[] args) {
int[][] map = new int[8][7];
for (int i = 0; i < 7; i++) {
map[0][i] = 1;
map[7][i] = 1; //1代表障碍
}
for (int i = 0; i < 8; i++) {
map[i][0] = 1;
map[i][6] = 1;
}
map[3][1] = 1;
map[3][2] = 1;
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
System.out.print(map[i][j] + "\t");
}
System.out.println();
}
System.out.println();
System.out.println();
/*-------------以上为布置迷宫并打印-------------------------*/
F f = new F();
f.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] + "\t");
}
System.out.println();
}
}
}
class F {
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)) { //下
return true;
} else if (findWay(map, i, j + 1)) { //右
return true;
} else if (findWay(map, i - 1, j)) { //上
return true;
} else if (findWay(map, i, j - 1)) { //左
return true;
} else {
map[i][j] = 3;
return false;
}
} else { //开始位置就是1, 2, 3balabala就为false
return false;
}
}
}
}
地图
路径