Java 老鼠走迷宫 汉诺塔

 

Labyrinth

public class Labyrinth {
  public static void main(String[] args){
    Map map=new Map();
    map.init();
    map.show();
    Mouse mouse=new Mouse();
    mouse.seek(map.map,1,1);
    map.show();
  }
}

class Mouse{
  // 0 可走, 1 不可走, 2 通路, 3 dead end
  public boolean seek(int[][] map,int i,int j){
    if(map[6][5]==2){  // end point标记为通路,路径已找到
      return true;
    }else{
      if(map[i][j]==0){  // 找的路必须为0,不能为2,防止死循环
        map[i][j]=2;
        if(seek(map,i+1,j)){
          return true;
        }else if(seek(map,i,j+1)){
          return true;
        }else if(seek(map,i-1,j)){
          return true;
        }else if(seek(map,i,j-1)){
          return true;
        }else{
          map[i][j]=3;
          return false;
        }
      }else{  // map[i][j]== 1, 2, 3
        return false;
      }
    }

  }
}

class Map{
  private final int row=8;
  private final int column=7;
  protected int[][] map;
  public void init(){
    map=new int[row][column];
    // 第一列和第7列置1
    for(int i=0;i<row;++i){
      map[i][0]=1;
      map[i][column-1]=1;
    }
    // 第一行和第8行置1
    for(int i=0;i<column;++i){
      map[0][i]=1;
      map[row-1][i]=1;
    }
    map[3][1]=1;
    map[3][2]=1;
  }
  public void show(){
    System.out.println("current map:");
    for(int i=0;i<row;++i){
      for(int j=0;j<column;++j){
        System.out.print(map[i][j]+" ");
      }
      System.out.println();
    }
  }
}

  

汉诺塔

public class Tower {
  public static void main(String[] args) {
    Hanoi hanoi = new Hanoi();
    hanoi.move(5, 'A', 'B', 'C');
  }
}

class Hanoi {
  // num: 盘数,a:A塔,b:B塔,c:C塔
  public void move(int num, char a, char b, char c) {
    if (num == 1) { // 只剩一个盘,出口
      System.out.println(a + " => " + c);
    } else {
      // 将多个盘看为2个, 最下的一个, 和上面的所有(num-1)
      move(num - 1, a, c, b); // 借助c, 将上面的num-1移动到 b
      System.out.println(a + " => " + c); // 最下面的移到c
      move(num - 1, b, a, c); // 借助a, 把b塔的num-1个移到c
    }
  }
}

  

 

posted @ 2021-06-20 16:46  ascertain  阅读(119)  评论(0编辑  收藏  举报