-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode.c
53 lines (40 loc) · 1.24 KB
/
node.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
#include "node.h"
#include <stdio.h>
#include <stdlib.h>
Node *generate_child_node(const Node *parent, const Direction direction) {
if (!is_valid_move(parent->state, direction)) {
return NULL;
}
Puzzle *new_state = (Puzzle *)malloc(sizeof(Puzzle));
if (!new_state) return NULL;
*new_state = *(parent->state);
move(new_state, direction);
Node *child = (Node *)malloc(sizeof(Node));
if (!child) {
free(new_state);
return NULL;
}
child->parent = (Node *)parent;
child->state = new_state;
child->move = direction;
child->cost = 0;
return child;
}
Node **generate_children(const Node *parent, int *num_children) {
Node **children = (Node **)malloc(DIRECTION_COUNT * sizeof(Node *));
*num_children = 0;
Direction directions[DIRECTION_COUNT] = {UP, DOWN, LEFT, RIGHT};
for (int i = 0; i < DIRECTION_COUNT; i++) {
Node *child = generate_child_node(parent, directions[i]);
if (child != NULL) {
children[(*num_children)++] = child;
}
}
return children;
}
void print_node(const Node *n, int debug) {
printf("Move: ");
print_direction(n->move);
printf("Cost: %d\n", n->cost);
print_puzzle(n->state, debug);
}