【发布时间】:2021-01-19 14:23:41
【问题描述】:
我用 C# 编写了一个类,用于计算二维数组中的相邻活细胞。假设我有一个这样的数组
int[,] array = new int[8, 8]
{
{3, 3, 3, 3, 3, 3, 3, 3},
{3, 0, 0, 0, 0, 0, 0, 3},
{3, 0, 0, 0, 1, 0, 0, 3},
{3, 0, 1, 0, 0, 1, 0, 3},
{3, 0, 1, 0, 0, 1, 0, 3},
{3, 0, 0, 1, 0, 0, 0, 3},
{3, 0, 0, 0, 0, 0, 0, 3},
{3, 3, 3, 3, 3, 3, 3, 3}
};
在这个数组中,0 是死细胞,1 是活细胞,3 是幽灵细胞。我的班级应该计算并返回0 和1 的所有相邻活细胞。对于这个数组,如果我要打印它应该返回的邻居
0 0 0 0 0 0 0 0
0 0 0 1 1 1 0 0
0 1 1 2 1 2 1 0
0 2 1 3 3 2 2 0
0 2 2 3 3 1 2 0
0 1 2 1 2 1 1 0
0 0 1 1 1 0 0 0
0 0 0 0 0 0 0 0
相反,它返回
0 0 0 0 0 0 0 0
0 0 0 1 1 1 0 0
0 1 1 1 1 1 1 0
0 1 1 1 1 1 1 0
0 1 1 1 1 1 1 0
0 1 1 1 1 1 1 0
0 0 1 1 1 0 0 0
0 0 0 0 0 0 0 0
对于任何给定的活细胞,它似乎只将邻居计数到1。这是我的课用来计算周围的活细胞
public static int NeighbourCount(int[,] array, int x, int y)
{
int neighours = 0;
if (array[x, y] != 3)
{
if (array[x + 1, y ] == 1) { neighours++; }
else if (array[x + 1, y - 1] == 1) { neighours++; }
else if (array[x , y - 1] == 1) { neighours++; }
else if (array[x - 1, y - 1] == 1) { neighours++; }
else if (array[x - 1, y ] == 1) { neighours++; }
else if (array[x - 1, y + 1] == 1) { neighours++; }
else if (array[x , y + 1] == 1) { neighours++; }
else if (array[x + 1, y + 1] == 1) { neighours++; }
}
return neighours;
}
我不明白为什么这只返回0's 和1's。知道是什么导致了这个问题吗?问题可能是我如何打印课程返回吗?我是这样打印的
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(0); j++)
{
Console.Write(NeighbourCount(array, i, j) + " ");
}
Console.WriteLine(string.Join(" ", ascii));
ascii.Clear();
}
任何关于什么问题的解决方案或想法将不胜感激!谢谢。
【问题讨论】:
-
变量
ascii是如何定义填充值的?