This will hang when there are no possible directions to move. Taking a simple example of your board with 4 by 4. Initially the board would be like
....
....
....
....
Initial position marked
A...
....
....
....
I make the first move, say I move RIGHT
AB..
....
....
....
I make the next move, say I move DOWN
AB..
.C..
....
....
I make the next move, say I move DOWN
AB..
.C..
.D..
....
I make the next move, say I move LEFT
AB..
.C..
ED..
....
I make the next move, say I move UP
AB..
FC..
ED..
....
And I am stuck, and I do not have any possible locations to move. Now a few more additions would fix your problem.
- Add a method to calculate the list of possible moving directions
- If no more moves are possible, exit the program
Hint
void calc_poss_dirs()
{
int dir;
poss_dir.count = 0;
for (dir = UP; dir <= RIGHT; dir++) {
if (can_move(dir)) {
poss_dir.dirs[poss_dir.count] = dir;
poss_dir.count++;
}
}
}
int can_move(int dir)
{
int x = cur_x;
int y = cur_y;
if (dir == UP)
x--;
else if (dir == DOWN)
x++;
else if (dir == LEFT)
y--;
else
y++;
if (!in_area(x, y))
return 0;
if (visited(x, y))
return 0;
return 1;
}