2

I have the following problem.

On a chessboard, I have a knight on a given square (shown in red), and I need to find the path the knight can take to reach another square (shown in green). enter image description here

I have to find the shortest path while obeying the movement rules of a knight in chess (L shaped moves) and count the number of moves:

like this:

enter image description here I have tried different things, but without success.

What can I do?

dreamcrash
  • 36,542
  • 23
  • 64
  • 87
Guilherme Lima
  • 481
  • 1
  • 3
  • 18

3 Answers3

4

You want to solve the problem in a finite amount of time, and want to favor short solutions. You should use a breadth-first search algorithm, trying out all possible moves from the starting point. Ignore moves that take the knight to squares that it has already visited.

Once you reach the destination point, you know you don't have to search for longer solutions, but you just finish enumerating all possible solutions with the same length as the first solution.

user3386109
  • 32,020
  • 7
  • 41
  • 62
G. Sliepen
  • 5,327
  • 1
  • 11
  • 25
2

I didn't check online to find any heuristic for this, but I can give you some inside tips about it:

Every square on the diagonal of the actual square of the Knight can be reached in only two moves, provided that the Knight is not in the corner. Square (x, y) to the squares (x-1, y+1), (x+1, y+1), (x+1, y-1) and (x-1, y-1) takes 2 moves;

  • The squares up, down, right, and left of the actual square takes 3 moves; Every square on the diagonal of the actual square with one square between them (e.g., actual square = c4, target square a6), takes 4 moves;

  • Every square on the diagonal of the actual square with a 2 squares between them (e.g., actual square = c4, target square f7), takes only 2 moves;

  • Finally, if you are in a square with a given color you will take an odd number of moves to reach the opposite color square. If the target square has the same color as the square that you are in it will take an even number of moves;

  • The number of steps that a Knight takes from a given position to another in a 8x8 board is at most 6.

I think you can make an algorithm that combines the above heuristics and adapted with the breadth-first search algorithm, that G. Sliepen has mentioned.

This answer might also help you. You also can find plenty of good answers here, with O(1) solutions.

dreamcrash
  • 36,542
  • 23
  • 64
  • 87
0

Dynamic Programming solution has the recurrence description of:

DP(x,y)= 1 + min(
              DP(x-2,y-1),DP(x-2,y+1),DP(x+2,y-1),DP(x+2,y+1),
              DP(x-1,y-2),DP(x-1,y+2),DP(x+1,y-2),DP(x+1,y+2)
          ); 

If I'm not mistaken, will require O(N^2) to memoize.

Adrian Colomitchi
  • 3,884
  • 1
  • 12
  • 23