Python uses a subset tree template based on the Backtracking Method to Solve the trojan board problem.
This article describes how Python solves the trojan board problem based on the subset tree template of the Backtracking Method. We will share this with you for your reference. The details are as follows:
Problem
Place the horse in a square on the 8x8 board of chess. The horse moves according to the chess rule and goes all over the 64 squares on the board, it is required that each square be entered only once to find a feasible solution.
Analysis
Note:This figure is a 5*5 board.
Similar to the Maze problem, but the solution length of this problem is fixed to 64
Each grid contains [(-), (-), (), (2,-1), (1,-2 ), (-1,-2), (-2,-1)] You can select 8 clockwise directions.
Going to a grid is called a step. Each step is regarded as an element, and eight directions are regarded as the state space of this step.
Apply the Backtracking Method to the subset tree template.
Code
'''Stepping board ''' n = 5 #8 is too slow. Change to 5 p = ), (2,-1), (1,-2), (-1,-2), (-2,-1)] # status space, 8 direction entry = () # departure location x = [None] * (n * n) # a solution with a fixed length of 64, such ), (4, 3),...] X = [] # A group of solutions # conflict Detection def conflict (k): global n, p, x, X # Step x [k] exceeds the boundary if x [k] [0] <0 or x [k] [0]> = n or x [k] [1] <0 or x [k] [1]> = n: return True # Step x [k] has passed if x [k] in x [: k]: return True return False # No conflict # backtracking (recursive Version) def subsets (k): # Reach the k-th element global n, p, x, X if k = n * n: # print (x), which is beyond the end of the element) # X. append (x [:]) # Save (a solution) else: for I in p: # traverse the state space of element x [k-1: 8 direction x [k] = (x [k-1] [0] + I [0], x [k-1] [1] + I [1]) if not conflict (k): # pruning subsets (k + 1) # test x [0] = entry # entry subsets (1) # Start step k = 1