-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtask11.c
87 lines (65 loc) · 1.43 KB
/
task11.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <stdio.h>
#include <stdlib.h>
#define YES "YES"
#define NO "NO"
// xy coordinate for knight movement on board
int move_x[] = { -1, 1, -2, 2, -2, 2, -1, 1 };
int move_y[] = { -2, -2, -1, -1, 1, 1, 2, 2 };
int ** alloc_board(int m, int n) {
int i;
int **board = NULL;
board = calloc(m, sizeof(int *));
if (board == NULL) {
printf("NO");
exit(1);
}
for (i = 0; i < m; i++) {
*(board + i) = calloc(n, sizeof(int));
if (*(board + i) == NULL) {
printf("NO");
exit(1);
}
}
return board;
}
void free_board(int **board, int m) {
int i;
for (i = 0; i < m; i++) {
free(*(board + i));
}
free(board);
}
int move(int **board, int m, int n, int sx, int sy, int moves) {
int i;
int next_x, next_y;
if (moves == m * n - 1) {
return 1;
}
for (i = 0; i < sizeof(move_x) / sizeof(int); i++) {
next_x = sx + move_x[i];
next_y = sy + move_y[i];
if (next_x < m && next_y < n && next_x >= 0 && next_y >= 0 && board[next_x][next_y] == 0) {
board[next_x][next_y] = 1;
if (move(board, m, n, next_x, next_y, moves + 1)) {
return 1;
} else {
board[next_x][next_y] = 0;
}
}
}
return 0;
}
int main() {
int **board;
int m, n, sx, sy;
scanf("%d%d%d%d", &m, &n, &sx, &sy);
if (m >= 20 || n >= 20 || sx > m || sy > n) {
printf(NO);
exit(1);
}
board = alloc_board(m, n);
board[sx - 1][sy - 1] = 1;
printf(move(board, m, n, sx - 1, sy - 1, 0) ? YES : NO);
free_board(board, m);
return 0;
}