Knights travel around (walking horse chessboard) and pruning analysis

I, entitled

There are points on a grid in nxn board (there is an nxn checkerboard point) of a Chinese chess horse, horse to go on the word.

Seeking a path to travel around the board, so that the horse can just take a final return to the starting position from a starting position along the path of each grid point.

 

Second, the idea

1, the initial ideas:

  First thought is to use DFS to resolve, not only can traverse globally can go back, then set out to do up, although DFS, but in this question, it is unnecessary to use adjacency matrix, an array does not need to determine whether to every point had envisaged a start is to use the board as a two-dimensional array, the default is all zeros, the initial point is 1, the next step is 2, so keep going until you go over, every time you need to determine the eight directions, if the go the direction of the left direction is still chessboard, to then determine the next step until you have gone through eight directions or have gone full board, return on a move.

 

2, back method:

  Uses a recursive thought, every step will create a priority queue, under the premise of the algorithm is not completed, as long as the priority queue is not empty, it will have been implemented.

 

 

3, encountered a problem:

But in the actual resolution process, each recursive need to pass an array of the current board, but the number of steps before being returned array will always be change, so I tried to use a dictionary to save each step moves, strange that each operation will change All values ​​in the dictionary, so that experimental error, after the switch to a three-dimensional array also encountered the same problem.

 

 

Shallow vs. deep copy problems:

  Both copy and clone functions have suffered the same problem after Baidu understand that this involves a shallow copy and deep copy and shallow copy process just quoted address of the array (actually point to the same space), a deep copy is really opened up a new space

Solution: In order to avoid trouble on the direct themselves with two for loop to copy the array, run, get normal results.

 

There is a function that comes when java, drawing on the last copy on all two-dimensional array assignment statement instead of the current two-dimensional array, the roommate tried on the computer as well. (unsolved)

 

 

Third, pruning

With the idea before, even though it can solve the problem, but still not enough, the board is not the answer almost ran 8 * 8, we need to think about pruning program to make the code run faster.

As it relates to the issue of the need for pruning specific issues to do meticulous research, so direct Baidu pruning program as follows:

 

 

According pruning program to transform your own code:

1, in order to calculate the number of each location to go the direction we need to add a method to determine a location several moves, only need to traverse the current point to eight directions, difficulty walking may be the preferred option a small number of points, at the beginning every time I take the most advantage, but found that this does not come to the end, and can not go back again, so we need to save up all walking every step of the number of points to go, so It may be back only when wrong, here uses a priority queue of this structure.

 

 

 Use the priority queue eliminating the need to write their own sorting algorithm to create arrays and need, we just need to give priority queue arrangement rules can be developed without the need to get to know their internal implementation. This has brought great convenience.

 

2, add a method to calculate the distance to the center of a location and then compare the distance can be realized in the priority queue 2 pruning.

 

3,  ultimately dynamic FIG.

https://img-blog.csdn.net/20131206223719718?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvY3JheW9uZGVuZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast

 

 

Four complexity: O (n + 8 ^ n)

DFS to the main algorithm, the time complexity (V views traversal + E recursive)

Suppose there are eight kinds of moves each vertex, is most often recursive 8 ^ N (N * N chessboard)

Sometimes time is very different in each case, there is a certain degree of particularity (pruning is not necessarily perfect)

 

 

Fifth, the implementation code

  . 1  public  class Horse {
   2      static  int n-; // n-n-* chessboard 
  . 3      static  int the FP [] [] = {{. 1, 2}, {. 1, -2}, {-1, 2}, {-1, -2}, {2, 1}, {2, -1}, {-2, 1}, {-2, -1}}; // eight possible directions away 
  . 4      static  int X0, yO; // starting 
  . 5      static  int [] [] [] Group;
   . 6  
  . 7      class Node { // this point, the number of coordinates and a direction to go 
  . 8          int X;
   . 9          int Y;
 10          int HP; // can take several directions
. 11          int DC; // distance from the center 
12 is  
13 is          public Node ( int I, int J, int K, int D) {
 14              the this .x = I;
 15              the this .y = J;
 16              the this .hp = K;
 . 17              the this = .dc D;
 18 is          }
 . 19      }
 20 is  
21 is      public  static comparator <Node> = idComparator new new comparator <Node> () { // comparison method priority queue (small to large far to near 
22         @Override
 23         public int compare(node n1, node n2) {
 24             if(n1.hp != n2.hp) {
 25                 return (int) (n1.hp - n2.hp);
 26             }else {
 27                 return n2.dc-n1.dc;
 28             }
 29         }
 30     };
 31 
 32     public void init() {
 33         Scanner sc = new Scanner(System.in);
 34         System.out.println("int n:");
35          n-= sc.nextInt ();
 36          Group = new new  int [n-n-* +. 1 ] [n-] [n-];
 37 [          System.out.println ( "Enter the starting point:" );
 38 is          X0 = sc.nextInt ();
 39          yO = sc.nextInt ();
 40          the DFS (X0, yO,. 1 );
 41 is      }
 42 is  
43 is      public  void the DFS ( int X, int Y, int now_pace) { // depth traversal horse 
44 is          IF ( Check (X, Y, now_pace)) {
 45              return;
 46         }
 47         copy(group[now_pace], group[now_pace - 1]);
 48         group[now_pace][x][y] = now_pace + 1;
 49         now_pace++;
 50         System.out.println(now_pace);
 51         ps(group[now_pace - 1]);
 52         System.out.println();
 53 
 54         if ((now_pace == n * n + 1 && ((Math.pow(x - x0, 2) + Math.pow(y - y0, 2) == 5)))) {// 判断是否走满且能回到原点
 55             System.out.println("okkkkk");
 56             System.exit(0);
 57             return ;
 58          }
 59  
60          Queue <Node> = nodePriorityQueue new new PriorityQueue <> (. 8, idComparator); // every time priority queues ascending 
61 is          for ( int [] P: the FP) { // iterate eight directions in the priority queue
 62 is              // int NPHS nextPosHasSteps = (X + P [0], Y + P [. 1], now_pace); 
63 is              nodePriorityQueue.add ( new new Node (X + P [0], Y + P [. 1] , nextPosHasSteps (X + P [0], Y + P [. 1 ], now_pace), disFromCenter (X, Y)));
 64          }
 65          the while ! (nodePriorityQueue.isEmpty ()) { // back 
66             = n-Node nodePriorityQueue.poll ();
 67              the DFS (NX, NY, now_pace);
 68          }
 69      }
 70  
71 is      public  Boolean Check ( int X, int Y, int now_pace) { // determines whether the board has been to or 
72          return X <0 || X> = Y n-|| <|| 0 Y> = n-|| Group [now_pace -. 1] [X] [Y] = 0! ;
 73 is      }
 74  
75      public  int nextPosHasSteps ( int X , int Y, int now_pace) { //Calculating the direction of the current position to go 
76          int Steps = 0 ;
 77          for ( int [] P: the FP) { // iterate eight directions determined 
78              IF ! (Check (X + P [0], Y + P [. 1 ], now_pace)) {
 79                  Steps ++ ;
 80              }
 81          }
 82          return Steps;
 83      }
 84      
85      public  int disFromCenter ( int X, int Y) { // distance from the center 
86          return ( int) (Math.pow(x-n/2, 2)+Math.pow(y-n/2, 2));
 87     }
 88 
 89     public void ps(int[][] s) {//打印数组
 90         for (int i = 0; i < s.length; i++) {
 91             for (int j = 0; j < s.length; j++) {
 92                 System.out.print(s[i][j] + " ");
 93             }
 94             System.out.println();
 95         }
 96     }
 97 
 98     public void copy(int[][] a, int[][] b) {
 99         for (int i = 0; i < a.length; i++) {
100             for (int j = 0; j < a.length; j++) {
101                 a[i][j] = b[i][j];
102             }
103         }
104     }
105 
106     public static void main(String[] args) {
107         Horse h = new Horse();
108         h.init();
109     }
110 }

Guess you like

Origin www.cnblogs.com/Unicron/p/11574784.html