这道题的关键在于出口都被堵住了,怎么让程序终止!!!
如果使用常规算法对于现在的知识储备,实在是有点烧脑。想了一个取巧的方案,就是利用概率,即如果程序循环500次还没有结束,默认已经走到死路,可以结束进程了(这个方法虽然有冒险性质,但是只有极小概率会导致程序提前退出)
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
int main(void)
{
char ch[10][10] = { 0 };
int row, column, i, n,a=0;
for (row = 0;row < 10;row++)
{
for (column = 0;column < 10;column++)
{
ch[row][column] = '.';
}
}
srand((unsigned)time(NULL));
row = 0;
column = 0;
ch[row][column] = 'A';
for (i='A';i < 90;)
{
a++;
n = rand() % 4;
switch (n)
{
case 0:
if (row > 0 && ch[row-1][column] == '.')
{
row = row - 1;
ch[row][column] = i + 1;
i++;
break;
}
else
break;
case 1:
if (column > 0 && ch[row][column-1] == '.')
{
column = column - 1;
ch[row][column] = i + 1;
i++;
break;
}
else
break;
case 2:
if (row < 9 && ch[row+1][column] == '.')
{
row = row + 1;
ch[row][column] = i + 1;
i++;
break;
}
else
break;
case 3:
if (column < 9 && ch[row][column+1] == '.')
{
column = column + 1;
ch[row][column] = i + 1;
i++;
break;
}
else
break;
}
if (a > 1000)
break;
}
for (row = 0;row < 10;row++)
{
for (column = 0;column < 10;column++)
{
printf(" %c", ch[row][column]);
}
printf("\n");
}
return 0;
}
|