分类: C/C++
2011-11-22 13:13:36
编写一个程序,生成一个贯穿10*10的字符数组(初始时全为字符‘.’)的“随机步法”,程序必须每次从一个元素走到另外一个元素,方向随机为前、后、左、右,元素按照访问顺序用字母A到Z标记,如果其中某个元素前后左右都已经有字母标记,则停止。
下面是我写的程序,思路是用随机数控制方向:
#include
#define N 10
#define UP 0
#define DOWN 1
#define LEFT 2
#define RIGHT 3
int main()
{
char a[N][N] = {'0'};
int i, j, dirc;
srand((unsigned)time(NULL));
printf("Program begins:\n");
for(i = 0; i < N; i++){//init a[N][N]
for(j = 0; j < N; j++){
if(i == 0 && j == 0)
a[i][j] = 'A';
else
a[i][j] = '.';
}
}
i = 0, j = 0;
while(1){
dirc = rand() % 4;//0 = up, 1 = down, 2 = left, 3 = right
printf("%d\n", dirc);
if(dirc == RIGHT && a[i][j+1] == '.' && (j + 1) < N){//move right
a[i][j + 1] = a[i][j] + 1;
j = j + 1;
}
else if(dirc == LEFT && a[i][j-1] == '.' && (j - 1) >= 0){//move left
a[i][j-1] = a[i][j] + 1;
j = j - 1;
}
else if(dirc == UP && a[i-1][j] == '.' && (i - 1) >= 0){//move up
a[i-1][j] = a[i][j] + 1;
i = i - 1;
}
else if(dirc == DOWN && a[i+1][j] == '.' && (i + 1) < N){//move down
a[i+1][j] = a[i][j] + 1;
i = i + 1;
}
if(a[i][j] == 'Z')//if mark to 'Z'..stop
break;
else if(a[i+1][j] != '.' && a[i-1][j] != '.' && a[i][j+1] != '.' && a[i][j-1] != '.')//if no direction to move...stop
break;
}
for(i = 0; i < N; i++){//print result
for(j = 0; j < N; j++){
printf("%c ",a[i][j]);
if(j == 9)
printf("\n");
}
}
}
程序大部分次数运行都正常,效果如图: