骑士位于(a,b)位置,需要将位于(c,d)的国王带走。我怎么能:
答:可视化游览
B:计算从(a,b)到(c,d)所需的最小步骤
我发现的实施基本上是棋盘上骑士的一系列动作,这样骑士只能访问每个方格一次,但我希望更具体,并进入一个特定的位置。
我应该寻找什么样的算法或策略?
我正在考虑使用python
答案 0 :(得分:1)
您可以使用BFS算法来实现上述目标。只需缓存访问过的位置,这样就不会多次访问某个位置。现在,无论何时访问目标,这是在每次完整迭代时所采取的最小步数,您只需要探索1度的分离。
假设N X M棋盘用Point代表棋盘上的每个棋盘并在其上应用BFS。
class Point{
int x;
int y;
int dist;
}
public int knight(int N, int M, int x1, int y1, int x2, int y2) {
Point source = new Point(x1, y1);
Point destination = new Point(x2, y2);
Queue<Point> q = new LinkedList<>();
q.add(source);
Set<Point> hset = new HashSet<>();
hset.add(source);
int[][] dir = {{1, 2}, {-1, 2}, {1, -2}, {-1, -2}, {2, 1}, {-2, 1}, {2, -1}, {-2, -1}};
while(!q.isEmpty()){
Point p = q.poll();
if(p.equals(destination)){
return p.dist;
}
for(int[] d : dir){
int row = p.x + d[0];
int col = p.y + d[1];
Point temp = new Point(row, col);
if(row <= 0 || col <= 0 || row > N || col > M || hset.contains(temp)){
continue;
}
temp.dist = p.dist + 1;
q.add(temp);
hset.add(temp);
}
}
return -1; //unreachable point from source position
}
可视化游览会更简单,只需使用ArrayList等来存储遍历的路径。 另一种方法可能是使用Dijkstra算法来实现上述目的。
答案 1 :(得分:0)
找到Knight游览问题的准确解决方案的最佳方法是使用Backtracking算法。看看你可以选择的所有可能的步骤(a,b)选择第一个步骤,然后继续前进,直到找到死路。
如果发生死胡同,请向后退一步并探索其他选项。
这是 DFS(Depth First Searh)
的示例