Chinaunix首页 | 论坛 | 博客
  • 博客访问: 324686
  • 博文数量: 15
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 179
  • 用 户 组: 普通用户
  • 注册时间: 2013-09-09 18:16
文章分类

全部博文(15)

文章存档

2019年(1)

2018年(1)

2015年(7)

2013年(6)

我的朋友

分类: Java

2013-09-12 16:53:03


点击(此处)折叠或打开

  1. package basic;

  2. public class KnightAll {

  3.     /**
  4.      * @param args
  5.      */
  6.     private final static int N = 4;
  7.     private final static int M = 5;
  8.     // 下一个出口的8个位置的相对坐标
  9.     private static int[][] nextPos = {{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};
  10.     
  11.     private static int total = 0;
  12.     static int prePosX; //下一个位置
  13.     static int prePosY; //下一个位置
  14.     public static void main(String[] args) {
  15.         int[][] chessBoard = new int[N][M];
  16.         int startX = 0;
  17.         int startY = 0;
  18.         chessBoard[startX][startY] = 1;
  19.         find(startX, startY, 2, chessBoard);
  20. //        for (int posX = 0; posX < N; posX++) {
  21. //            for (int posY = 0; posY < N; posY++) {
  22. //                int[][] chessBoard = new int[N][N];
  23. //                find(posX, posY, 2, chessBoard);
  24. //            }
  25. //        }
  26.         System.out.println(total);
  27.     }
  28.     
  29.     public static void find(int x, int y, int dep, int[][] chessBoard) {
  30.         int i, xx, yy;
  31.         for (i = 0; i <= 7; i++) {
  32.             xx = x + nextPos[i][0];
  33.             yy = y + nextPos[i][1];
  34.             // 判断新坐标是否出界,是否已走过
  35.             if (isInboard(xx, yy) && chessBoard[xx][yy] == 0) {
  36.                 chessBoard[xx][yy] = dep;
  37.                 if (dep == N * M) {
  38.                     total++;
  39.                     printChessBoard(chessBoard);
  40.                     System.out.println("##################################");
  41.                 } else {
  42.                     // 从新坐标出发,递归下一层
  43.                     find(xx, yy, dep + 1, chessBoard);
  44.                 }
  45.                 // 回溯,恢复未走标志
  46.                 chessBoard[xx][yy] = 0;
  47.             }
  48.         }
  49.     }

  50.     
  51.     //计算位置是否在棋盘内
  52.     public static boolean isInboard(int posX, int posY) {
  53.         return 0 <= posX && posX < N && 0 <= posY && posY < M;
  54.     }
  55.     
  56.     //打印结果
  57.     public static void printChessBoard(int[][] chessBoard) {
  58.         for (int i = 0; i < N; i++) {
  59.             for (int j = 0; j < M; j++) {
  60.                 System.out.print(chessBoard[i][j] + "\t");
  61.             }
  62.             System.out.println();
  63.         }
  64.     }

  65. }


阅读(2056) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~