这是我试图用C:http://i.stack.imgur.com/X70nX.png解决的问题
我写了这段代码,但我不知道出了什么问题。它没有给我任何输出,只是一个空屏幕
这是我的准则:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <stdbool.h>
#define ROW 10
#define COL 10
#define RIGHT 0
#define UP 1
#define LEFT 2
#define DOWN 3
int main(void)
{
char mat[ROW][COL];
bool try;
int move, co, ro,letter;
//Filling the grid with "."
for (ro = 0; ro < ROW; ro++)
{
for (co = 0; co < COL; co++)
mat[ro][co] = '.';
}
//Initial Values
co = 0; ro = 0; mat[0][0] = 'A';
srand((unsigned)time(NULL));
for (letter = 1; letter < 26; letter++)
{
try = true;
while (try)
{
move = rand() % 4;
if ((move == RIGHT) && (co + 1 < COL) && (mat[ro][co+1]=='.'))
{
mat[ro][co + 1] = mat[ro][co] + 1;
co++; try=false;
}
if ((move == UP) && (ro - 1 >= 0) && (mat[ro-1][co]=='.') )
{
mat[ro - 1][co] = mat[ro][co] + 1;
ro--; try = false;
}
if ((move == LEFT) && (co - 1 >= 0) && (mat[ro][co-1]=='.'))
{
mat[ro][co - 1] = mat[ro][co] + 1;
co--; try = false;
}
if ((move == DOWN) && (ro + 1 < ROW) && (mat[ro+1][co]=='.'))
{
mat[ro + 1][co] = mat[ro][co] + 1;
ro++;
}
}
}
//Printing The GRID
for (ro = 0; ro < ROW; ro++)
{
for (co = 0; co < COL; co++)
printf(" %c", mat[ro][co]);
printf("\n");
}
return 0;
}
现在,对于同样的问题有一个类似的讨论:10x10阵列上的随机游动
但我还是不知道我的代码有什么问题!请把我当作初学者吧。
修改:这是在考虑到评论后的新版本:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <stdbool.h>
#define ROW 10
#define COL 10
#define RIGHT 0
#define UP 1
#define LEFT 2
#define DOWN 3
int main(void)
{
char mat[ROW][COL];
bool try;
int move, co, ro,letter,blocked;
//Filling the grid with "."
for (ro = 0; ro < ROW; ro++)
{
for (co = 0; co < COL; co++)
mat[ro][co] = '.';
}
//Initial Values
co = 0; ro = 0; mat[0][0] = 'A';
srand((unsigned)time(NULL));
for (letter = 1; letter < 26; letter++)
{
try = true;
blocked = 0;
while (try)
{
move = rand() % 4;
switch (move)
{
case RIGHT:
{ if ((co + 1 < COL) && (mat[ro][co + 1] == '.'))
{
mat[ro][co + 1] = mat[ro][co] + 1;
co++; try = false; break;
}
else { blocked++; break; }}
case UP:
{ if ((move == UP) && (ro - 1 >= 0) && (mat[ro - 1][co] == '.'))
{
mat[ro - 1][co] = mat[ro][co] + 1;
ro--; try = false; break;
}
else { blocked++; break; }}
case LEFT:
{ if ((move == LEFT) && (co - 1 >= 0) && (mat[ro][co - 1] == '.'))
{
mat[ro][co - 1] = mat[ro][co] + 1;
co--; try = false; break;
}
else { blocked++; break; }}
case DOWN:
{if ((move == DOWN) && (ro + 1 < ROW) && (mat[ro + 1][co] == '.'))
{
mat[ro + 1][co] = mat[ro][co] + 1;
ro++; try = false; break;
}
else { blocked++; break; }}
}
if (blocked == 4)
{try = false; letter=26;}
}
}
//Printing The GRID
for (ro = 0; ro < ROW; ro++)
{
for (co = 0; co < COL; co++)
printf(" %c", mat[ro][co]);
printf("\n");
}
return 0;
}
代码有时只工作,但在“Z”之后不停止(它应该是letter=26),
发布于 2013-12-22 15:35:20
代码在(有时是)中工作。我认为你经常进入一个无限循环,因为你产生了一个随机游动,这是不可能继续的。如下所示:
A B C .
H I D .
G F E .
. . . .
https://stackoverflow.com/questions/20730936
复制相似问题