【发布时间】:2015-05-15 01:51:55
【问题描述】:
在准备面试的时候,遇到了这个问题,我理解但不明白如何获得解决方案。
假设你有这个板(在这种情况下是 4 行 3 列的矩阵,但它可以是 N 行和 M 列长)
A[0][0] = 0 A[0][1] = 0 A[0][2] = 0
A[1][0] = 0 A[1][1] = 0 A[1][2] = 1
A[2][0] = 1 A[2][1] = 0 A[2][2] = 0
A[3][0] = 0 A[3][1] = 0 A[3][2] = 0
你会如何计算一个骑士从左上角到右下角的最小回合数?
0 表示该特定方格上没有棋子,而 1 表示该方格上有棋子。
在这种情况下,骑士需要 7 回合才能移动到右下角:
in the first turn the knight moves from square (0, 0) to square (2, 1);
in the second turn the knight moves from square (2, 1) to square (0, 2);
in the third turn the knight moves from square (0, 2) to square (1, 0);
in the fourth turn the knight moves from square (1, 0) to square (2, 2);
in the fifth turn the knight moves from square (2, 2) to square (3, 0);
in the sixth turn the knight moves from square (3, 0) to square (1, 1);
in the seventh turn the knight moves from square (1, 1) to square (3,4).
最好的情况显然是 3,但那些方块(A[1][2] 和 A[2][0])被挡住了。
实现这一点的最佳方法是什么?我在网上读到 BFS 会这样做,但我什至不知道从哪里开始编写这个 Python。提前致谢。
下面是函数的外观:
def shortest_path(matrix):
#passing in [[0, 0, 0], [0, 0, 1], [1, 0, 0], [0, 0, 0]]
【问题讨论】:
-
请向我们展示您到目前为止所做的尝试。
-
不清楚您遇到了什么具体问题。
-
我正在计算一个骑士从棋盘的左上角到右下角的最小转数。我没有实现,因为我不确定如何解决问题。
-
我相信这是Knight's tour问题的变体。
-
@JamesMills 不完全是,Knight's tour 问题在图中要求Hamiltonian path,这个问题只是要求两点之间的最短路径。
标签: python algorithm graph shortest-path minimization