Horses go day problems - backtracking (python && JAVA)

Understanding of the eight queens problem we'll look pretty much the same horse go day problems.

Problem Description: The chessboard n * m, the horse can only take the "day". Horses from position (x, y), the board of each cell are gone once and only once away. Find all paths.

 Our 5 * 4 as an example, or the numbers on each grid are marked. Each number is two, ten digits represent the row of the grid is located, and two-digit row of the grid is located.

 This problem is also a two limiting conditions: 1. each grid are gone, and each grid go only once. 2. You must go on the word

So what the Japanese word you are gone? What law do?

1. The lower left upper right cross-jump method on the word (the difference between the initial number of grid squares with termination 8)

             

 2. The left upper right lower cross-jump method on the word (the difference between the starting number of squares with the checker 12 is terminated)

               

 3. The lower left upper right word on vertical jumps (the difference between the starting grid with a grid of 19 numbers of termination)

         

4 . Word on the upper left lower right vertical jumps (the difference between the starting grid with a grid of numbers terminate 21)

          

Restrictions found, we are still looking for "horse" storage structure, where we still choose a one-dimensional array: Because each grid can only take once, so it is in line with one-dimensional array of storage features, namely an index corresponds to one element.

python implementation:

while True:
    arr1 = []
    n = int(input("棋盘行数:"))                       #输入行数
    m = int(input("棋盘列数:"))                       #输入列数
    xx = int(input("起始行标:"))                      #输入起始行标号
    yy = int(input("起始列标:"))                      #输入起始列标号
    for x in range(n):
        for y in range(m):
            a = 10*x+y                                #通过行列转换成方格中的数字
            arr1.append(a)
    num = 0
    def  horse(arr,finish_line=1):
        arr[0] = xx*10+yy                              #通过起始位置的行列标号转换成起始位置方格中的数字
        flag = True
        if finish_line == len(arr):
            global num
            num += 1
            print("第%s种走法:" %num)
            for i in arr:                               #将方格中的元素转化为下标的形式输出
                mm = str(int(i/10))
                nn = str(int(i%10))
                print("("+mm+","+nn+")")
            # print(arr)
            return 0
        for stand in arr1:                              #保证马一直在棋盘范围内活动
            arr[finish_line] = stand
            # print(arr)
            if finish_line >= 1:                         #从初始位置的下一个位置判断是否与上一个位置成日字
                if abs(arr[finish_line] - arr[finish_line - 1]) != 8 and abs(arr[finish_line] - arr[finish_line - 1]) != 12 and abs(arr[finish_line] - arr[finish_line - 1]) != 19 and abs(arr[finish_line] - arr[finish_line - 1]) != 21:
                    flag = False
                else:
                    flag = True
            for line in range(finish_line):
                if arr[finish_line] == arr[line]:        #判断当前位置之前是否被走过
                    flag = False
            if flag == True:
                horse(arr,finish_line+1)
    if __name__ == '__main__':
        horse([None]*n*m)
        print("
一共%s种走法" %num)

JAVA实现:

import java.util.Scanner;
import java.util.Arrays;
public class horse {
    public static int num=0;
//    public static int []arr1 = new int[20];
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);           //初始化的输入操作
        System.out.println("棋盘高:");
        int height = sc.nextInt();
        System.out.println("棋盘宽:");
        int width = sc.nextInt();
        System.out.println("起始横坐标:");
        int startx = sc.nextInt();
        System.out.println("起始纵坐标:");
        int starty = sc.nextInt();
        int []arr = new int[height*width];
        int []arr1 = new int[height*width];            //arr1列表用来存放所有格子,同时保证了出界的问题
              int i=0;
              for(int x=0; x<height; x++){
                 for(int y=0; y<width;y++){
                     arr1[i++]=10*x+y;
             }
          }
        System.out.println(Arrays.toString(arr1));
        arr[0] = 10*startx+starty;
        int finish_index = 1;
        int node_num = height*width;
        horse_ri(arr,arr1,finish_index);
        System.out.printf("共%d种走法",num);
    }
    static void horse_ri(int arr[],int arr1[],int finish_index){
         boolean flag=true;
         if(finish_index==arr.length){           
           num++;
           System.out.printf("第%d种走法",num);
           System.out.println(Arrays.toString(arr));
           return;
         }
         for(int ind=1;ind<arr1.length; ind++){
             arr[finish_index]=arr1[ind];
             flag = true;
//不是日字的情况
if((Math.abs(arr[finish_index]-arr[finish_index-1])!=8)&&(Math.abs(arr[finish_index]-arr[finish_index-1])!=12)&&(Math.abs(arr[finish_index]-arr[finish_index-1])!=19)&&(Math.abs(arr[finish_index]-arr[finish_index-1])!=21)){ flag = false; }
//之前走过的格子
for(int index=0;index<finish_index;index++){ if(arr[finish_index]==arr[index]){ flag = false; } } if(flag==true){ horse_ri(arr,arr1,finish_index+1); } } } }

Guess you like

Origin www.cnblogs.com/daimaxiaocai/p/12124624.html