我正在尝试解决Java中的Knight巡回问题。
我的目标是计算任何尺寸的棋盘上一匹马的所有可能行程。我尝试使用的是邻接表数据结构。现在的问题是,我知道哪些正方形与一个正方形相邻,但是我不知道相邻的正方形在哪个方向。我该如何解决?
最佳答案
这只是您应该做什么的粗略概述:
样本方类:
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;
}
}
}
关于java - 带有邻接表的Knight巡回算法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34711701/