Код: Выделить всё
num_size = 5
path_list = []
DirX = [2, 1, -1, -2, -2, -1, 1, 2]
DirY = [1, 2, 2, 1, -1, -2, -2, -1]
def isSafe(i, j, n, Board):
return i >= 0 and j >= 0 and i < n and j < n and Board[i][j] == 0
isPossible = False
def knightTour(ChessBoard, path, N, x, y, visited=1):
global isPossible
ChessBoard[x][y] = visited
if visited==N*N :
isPossible = True
global path_list
path_list.append(path)
ChessBoard[x][y] = 0
return
for i in range(8):
newX = x + DirX[i]
newY = y + DirY[i]
if isSafe(newX, newY, N, ChessBoard) and not ChessBoard[newX][newY]:
knightTour(ChessBoard, path+[(newX,newY)], N, newX, newY, visited + 1)
ChessBoard[x][y] = 0
if __name__ == "__main__":
ChessBoard = np.array([[0 for j in range(num_size)] for i in range(num_size)])
knightTour(ChessBoard, [(0,0)], num_size, 0, 0)
Подробнее здесь: https://stackoverflow.com/questions/790 ... ights-tour