具有邻接列表的骑士巡回算法

时间:2016-01-10 22:49:25

标签: java depth-first-search

我试图用Java解决Knight的游览问题。 我的目标是在任何尺寸的棋盘上计算所有可能的马匹之旅。我试图使用的是adjadency-lists数据结构。现在的问题是,我知道哪个方块与一个正方形相邻,但我不知道相邻方块的方向。我将如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

这里只是概述了你应该做的事情:

  1. 制作" Square"带有向上,向下,向左和向右字段的类(加上访问器和修改器方法)
  2. 制作" Chessboard"用于存储所有方块并设置它们的类。
  3. 制作"骑士"在棋盘上移动的类(并检查移动是否有效)。
  4. 最后,创建一个驱动程序类,搜索并存储如何移动Knights。
  5. 示例Square类:

    public class Square
    {
        public final Square up;
        public final Square down;
        public final Square left;
        public final Square right;
        public Square(Square up, Square down, Square left, Square right)
        {
            this.up=up;
            this.down=down;
            this.left=left;
            this.right=right;
        }
        public Square getUp(){return up;}
        public Square getDown(){return down;}
        public Square getLeft(){return left;}
        public Square getRight(){return right;}
    }
    

    示例骑士类:

    public class Knight
    {
        private Square mySquare;
    
        public Knight(Square start)
        {
            mySquare = start;
        }
    
        /*  7 0
         * 6    1
         * 
         * 5    2
         *  4 3   
         */
        public boolean move(int dir)
        {
            switch(dir)
            {
            case 0: try{
               mySquare=mySquare.getUp().getUp().getRight(); return true;
            } catch (NullPointerException e) {return false}
            case 1: try{
               mySquare=mySquare.getUp().getRight().getRight(); return true;
            } catch (NullPointerException e) {return false}
            case 2: try{
               mySquare=mySquare.getDown().getRight().getRight(); return true;
            } catch (NullPointerException e) {return false}
            case 3: try{
               mySquare=mySquare.getDown().getDown().getRight(); return true;
            } catch (NullPointerException e) {return false}
            case 7: try{
               mySquare=mySquare.getUp().getUp().getLeft(); return true;
            } catch (NullPointerException e) {return false}
            case 6: try{
               mySquare=mySquare.getUp().getLeft().getLeft(); return true;
            } catch (NullPointerException e) {return false}
            case 5: try{
               mySquare=mySquare.getDown().getLeft().getLeft(); return true;
            } catch (NullPointerException e) {return false}
            case 4: try{
               mySquare=mySquare.getDown().getDown().getLeft(); return true;
            } catch (NullPointerException e) {return false}
            default: return false;
            }
        }
    }