有一个维度为 9x9 的二维数组。 Ant 从单元格 (5,5) 或中心开始。它随机向北、向南、向东或向西移动。当 Ant 从网格上掉下来时,它就会停止行走。它掉落的空间用 X 标记。在矩阵中,它应该显示 Ant 访问每个单元格的次数以及 Ant 掉落的移动次数。
我不知道从哪里开始或如何去做。比如如何制作北、南、西、东方法。
这是我到目前为止所拥有的。
public static void main(String [] args)
{
int [][] grid = new int[9][9];
for (int r = 0; r< grid.length; r++)
{
for (int c = 0 ; c<grid[0].length; c++)
{
grid[r][c] = 0;
}
}
boolean test = true;
while(test)
{
int random = (int)Math.random()*4+1;
if (random == 1)
{
}
else if (random == 2)
{
}
else if (random == 3)
{
}
else if (random == 4)
{
}
}
}
最佳答案
你的想法是正确的,现在你要做的就是按照随机指定的方向移动,并增加数组中的值。这是我的做法。
int count = 0;
int x = 4;
int y = 4; // arrays are 0 based
while(true)
{
int random = (int)Math.random()*4+1;
if (random == 1)
{
x--; // move left
}
else if (random == 2)
{
x++; // move right
}
else if (random == 3)
{
y--; // move down
}
else if (random == 4)
{
y++; // move up
}
if(x < 0 || y < 0 || x >= grid.length || y >= grid[x].length) break;
count++;
grid[x][y]++;
}
System.out.println(count); // number of moves before it fell
关于Java Antwalk - 二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20321181/