这是 Python 中一个非常低效的解决方案。你应该能够跟上。我不想只是用你自己的语言给出答案:P
class Finder:
def __init__(self, board, n, x, y):
self.board = board
self.n = n
# Create a copy of the board.
self.copy = []
for i in range(n):
row = []
self.copy += [row]
for j in range(n):
row += [False]
# The best move sequence (longest).
self.best = []
# The current move sequence.
self.move = []
self.find(x, y)
def valid_move(self,x1, y1, x2, y2):
# Don't move off the board!
if x2 < 0 or x2 > self.n - 1 or y2 < 0 or y2 > self.n - 1:
return False
# Don't go somewhere we've gone before!
if self.copy[y2][x2]:
return False
# See if this is a valid move.
a = self.board[y1][x1]
b = self.board[y2][x2]
return a[0] == b[0] or \
a[0] == b[1] or \
a[1] == b[0] or \
a[1] == b[1]
def find(self,x, y):
self.move += [(x, y, board[y][x])]
self.copy[y][x] = True
# If this is the best path, then create a copy.
if len(self.move) > len(self.best):
self.best = list(self.move)
# Short-circuit if the optimal route is found.
if len(self.best) == self.n * self.n:
return
newX = x - 1
newY = y
if self.valid_move(x, y, newX, newY):
self.find(newX, newY)
newX = x
newY = y - 1
if self.valid_move(x, y, newX, newY):
self.find(newX, newY)
newX = x + 1
newY = y
if self.valid_move(x, y, newX, newY):
self.find(newX, newY)
newX = x
newY = y + 1
if self.valid_move(x, y, newX, newY):
self.find(newX, newY)
# Clean up by removing the last move.
self.move = self.move[:-1]
self.copy[y][x] = False
# The board
board = \
[["AB", "XX", "DE"],
["BB", "FE", "DD"],
["BC", "CC", "CD"],
]
# The size of the board.
n = 3
# Find!!
finder = Finder(board, n, 0, 0)
for row in board:
print(row)
# Print empty line.
print()
for move in finder.best:
print(move)
这是输出:
['AB', 'XX', 'DE']
['BB', 'FE', 'DD']
['BC', 'CC', 'CD']
(0, 0, 'AB')
(0, 1, 'BB')
(0, 2, 'BC')
(1, 2, 'CC')
(2, 2, 'CD')
(2, 1, 'DD')
(2, 0, 'DE')