Skip to content

Commit

Permalink
Refactor move function to return success status
Browse files Browse the repository at this point in the history
  • Loading branch information
Vianpyro committed Sep 11, 2024
1 parent a9b610c commit 727b5dc
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 6 deletions.
8 changes: 6 additions & 2 deletions node.c
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ Node *generate_child_node(const Node *parent, const Direction direction) {

*new_state = *(parent->state);

move(new_state, direction);
// Free new_state if move fails
if (!move(new_state, direction)) {
free(new_state);
return NULL;
}

Node *child = (Node *)malloc(sizeof(Node));
if (!child) {
Expand All @@ -24,7 +28,7 @@ Node *generate_child_node(const Node *parent, const Direction direction) {
child->parent = (Node *)parent;
child->state = new_state;
child->move = direction;
child->cost = 0;
child->cost = parent->cost + 1;

return child;
}
Expand Down
8 changes: 5 additions & 3 deletions puzzle.c
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ int is_valid_move(const Puzzle *p, const Direction direction) {
}
}

void move(Puzzle *p, const Direction direction) {
int move(Puzzle *p, const Direction direction) {
int blank_row = p->blank_index / PUZZLE_SIZE;
int blank_col = p->blank_index % PUZZLE_SIZE;

Expand All @@ -106,16 +106,18 @@ void move(Puzzle *p, const Direction direction) {
new_col++;
break;
case NONE:
return;
return 0; // No move made
}

if (new_row < 0 || new_row >= PUZZLE_SIZE || new_col < 0 || new_col >= PUZZLE_SIZE) {
return;
return 0; // Move is out of bounds
}

int new_index = new_row * PUZZLE_SIZE + new_col;
swap(&p->board[p->blank_index], &p->board[new_index]);
p->blank_index = new_index;

return 1; // Move successful
}

void print_puzzle(const Puzzle *p, int debug) {
Expand Down
2 changes: 1 addition & 1 deletion puzzle.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ int get_blank_index(const Puzzle *p);
int get_inversion_count(const Puzzle puzzle);
int is_solvable(const Puzzle puzzle);
int is_valid_move(const Puzzle *p, const Direction direction);
void move(Puzzle *p, const Direction direction);
int move(Puzzle *p, const Direction direction);
void print_puzzle(const Puzzle *p, int debug);
void shuffle(Puzzle *p);
void swap(int *a, int *b);
Expand Down

0 comments on commit 727b5dc

Please sign in to comment.