The problem is to find the minimum number of moves that a knight will take to go from one square to another on a 'n' cross 'n' chessboard. The code below is based on backtracking. It works well until n
equals 5
but from n
equals 6
the time limit is exceeded on ideone. How can I make the code more efficient?
#include <stdio.h>
int minimum(int a, int b)
{
/* Returns the minimum of two numbers */
if (a <= b) {
return a;
} else {
return b;
}
}
int minmoves(int r1, int c1, int r2, int c2, int array[10][10], int n)
{
int moves;
/*
* If the place is already occupied dont go to it otherwise it will
* lead to a infinite loop so we return a large value so that the
* knight does not take this path
*/
if (array[r2][c2] == 1) {
return 32764;
}
/* We cannot go outside the board */
if ((r2 < 0) || (r2 > n - 1) || (c2 < 0) || (c2 > n - 1)) {
return 32764;
}
/* Condition to check if the path is complete */
if ((r1 == r2) && (c1 == c2)) {
return 0;
}
/* We add the point with coordinates r2, c2 to the path */
array[r2][c2] = 1;
/* All the possible moves that a knight can make */
moves = 1 + minmoves(r1, c1, r2 - 2, c2 - 1, array);
moves = minimum(moves, 1 + minmoves(r1, c1, r2 - 2, c2 + 1, array));
moves = minimum(moves, 1 + minmoves(r1, c1, r2 - 1, c2 - 2, array));
moves = minimum(moves, 1 + minmoves(r1, c1, r2 - 1, c2 + 2, array));
moves = minimum(moves, 1 + minmoves(r1, c1, r2 + 1, c2 - 2, array));
moves = minimum(moves, 1 + minmoves(r1, c1, r2 + 1, c2 + 2, array));
moves = minimum(moves, 1 + minmoves(r1, c1, r2 + 2, c2 - 1, array));
moves = minimum(moves, 1 + minmoves(r1, c1, r2 + 2, c2 + 1, array));
array[r2][c2] = 0;
return moves;
}
int main()
{
int r1, c1, r2, c2, x, i, j, n;
int array[10][10];
scanf("%d\n%d\n%d\n%d\n%d", &r1, &c1, &r2, &c2, &n);
/* All the elements of array are initialised to zero */
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
array[i][j] = 0;
printf("0 ");
}
}
x = minmoves(r1, c1, r2, c2, array, n);
printf("%d",x);
return 0;
}
minmoves
into lookup table in order to reuse them in subsequent iterations. But I am pretty sure there is an analytical solution... \$\endgroup\$