-
Notifications
You must be signed in to change notification settings - Fork 0
/
knight.c
71 lines (60 loc) · 1.43 KB
/
knight.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <stdio.h>
#define N 8
int is_valid(int i, int j, int sol[N + 1][N + 1])
{
if (i >= 1 && i <= N && j >= 1 && j <= N && sol[i][j] == -1)
return 1;
return 0;
}
int knight_tour(int sol[N + 1][N + 1], int i, int j, int step_count, int x_move[], int y_move[])
{
if (step_count == N * N)
return 1;
int k;
for (k = 0; k < 8; k++)
{
int next_i = i + x_move[k];
int next_j = j + y_move[k];
if (is_valid(i + x_move[k], j + y_move[k], sol))
{
sol[next_i][next_j] = step_count;
if (knight_tour(sol, next_i, next_j, step_count + 1, x_move, y_move))
return 1;
sol[i + x_move[k]][j + y_move[k]] = -1; // backtracking
}
}
return 0;
}
int start_knight_tour()
{
int sol[N + 1][N + 1];
int i, j;
for (i = 1; i <= N; i++)
{
for (j = 1; j <= N; j++)
{
sol[i][j] = -1;
}
}
int x_move[] = {2, 1, -1, -2, -2, -1, 1, 2};
int y_move[] = {1, 2, 2, 1, -1, -2, -2, -1};
sol[1][1] = 0; // placing knight at cell(1, 1)
if (knight_tour(sol, 1, 1, 1, x_move, y_move))
{
for (i = 1; i <= N; i++)
{
for (j = 1; j <= N; j++)
{
printf("%d\t", sol[i][j]);
}
printf("\n");
}
return 1;
}
return 0;
}
int main()
{
printf("%d\n", start_knight_tour());
return 0;
}