我有一个整天都在工作的程序。该程序冻结更多次,然后不冻结...。当不冻结时,它工作正常,看起来像这样...
http://picpaste.com/Multidimensional_Array-KfdKSmoE.bmp
当它确实在打开时挂断时,它将看起来像这样……
http://picpaste.com/Multidimensional_Array_hung-Jcmz0rQP.bmp
// Chapter 8 Programming Project #9
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 10
#define PATH_SIZE 25
#define ROW_SIZE ((int) (sizeof(board) / sizeof(board[0])))
int main(void)
{
char board[SIZE][SIZE] = {};
// 0 = Up, 1 = Down, 2 = Left, 3 = Right
unsigned short i = 0, x, y;
// Generate a random number
srand((unsigned) time(NULL));
int dir = rand() % 4;
// Set all positions of board to '.'
for (x = 0; x < ROW_SIZE; x++) {
for (y = 0; y < ROW_SIZE; y++)
board[x][y] = '.';
}
x = 0;
y = 0;
board[0][0] = 'A';
// Generate the path
while (i != PATH_SIZE) {
for (i = 0; i < PATH_SIZE;) {
// Check the direction and replace that char
switch (dir) {
case 0: if ((y - 1) >= 0 && (y - 1) < ROW_SIZE
&& board[x][y - 1] == '.') {
board[x][--y] = i + 'B';
++i;
} break;
case 1: if ((y + 1) >= 0 &&(y + 1) < ROW_SIZE
&& board[x][y + 1] == '.') {
board[x][++y] = i + 'B';
++i;
} break;
case 2: if ((x - 1) >= 0 && (x - 1) < ROW_SIZE
&& board[x - 1][y] == '.') {
board[--x][y] = i + 'B';
++i;
} break;
case 3: if ((x + 1) >= 0 && (x + 1) < ROW_SIZE
&& board[x + 1][y] == '.') {
board[++x][y] = i + 'B';
++i;
} break;
}
// Reset the random direction
dir = rand() % 4;
}
}
// Print the board
for (x = 0; x < ROW_SIZE; x++) {
for (y = 0; y < ROW_SIZE; y++)
printf("%c ", board[x][y]);
printf("\n");
}
return 0;
}
最佳答案
当没有可能的方向移动时,它将挂起。举一个简单的4乘4的板示例。最初,板像
....
....
....
....
初始位置标记
A...
....
....
....
我先走,说我向右走
AB..
....
....
....
我下一步,说我向下
AB..
.C..
....
....
我下一步,说我向下
AB..
.C..
.D..
....
我继续前进,说我向左移动
AB..
.C..
ED..
....
我下一步,说我向上
AB..
FC..
ED..
....
而且我被卡住了,而且我没有任何可移动的位置。现在,再添加一些内容可以解决您的问题。
添加一种方法来计算可能的移动方向列表
如果无法再移动,请退出程序
暗示
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;
}