所以我是初学者,我正在构建一个 C# Crozzle 游戏。我试图在二维数组中找到可以存储单词的空间。因此,例如,我有一个像这样的二维数组:
[ 0 1 1 0 0 0 0 ]
[ 0 1 1 0 1 1 1 ]
[ 0 1 1 0 1 1 1 ]
[ 0 1 1 0 1 1 1 ]
[ 0 1 1 0 1 1 1 ]
0 表示单元格为空,1 表示它包含一个值。我想获得一组免费的坐标。 所以最终我想存储起始和结束坐标,例如: [0,0] -> [0,4], [3,0] -> [3,4], [3,0] -> [6,0]
存储它们不是问题,问题是找到这些 0 的模式。有人知道解决这个问题的最佳方法吗?
谢谢!
最佳答案
您必须扫描二维数组的行和列。为了展示这个想法,我选择了
Tuple<int, int>
Tuple<Point, Point>
对应地表示一维和二维数组中的范围。当然,那个 Tuple<Point, Point>
不是一个好的选择,您可能想为某些量身定制的类(class)更改它。
private static IEnumerable<Tuple<int, int>> ScanLine<T>(IEnumerable<T> source, T sample, int atLeast) {
int count = 0;
int index = -1;
foreach (var item in source) {
index += 1;
if (Object.Equals(item, sample))
count += 1;
else {
if (count >= atLeast)
yield return new Tuple<int, int>(index - count, index - 1);
count = 0;
}
}
if (count >= atLeast)
yield return new Tuple<int, int>(index - count + 1, index);
}
private static IEnumerable<Tuple<Point, Point>> ScanBoard<T>(T[,] source, T sample, int atLeast) {
// Lines scan
for (int i = 0; i < source.GetLength(0); ++i) {
var line = Enumerable.Range(0, source.GetLength(1)).Select(c => source[i, c]);
foreach (var item in ScanLine(line, sample, atLeast))
yield return new Tuple<Point, Point>(new Point(item.Item1, i), new Point(item.Item2, i));
}
// Columns scan
for (int i = 0; i < source.GetLength(1); ++i) {
var line = Enumerable.Range(0, source.GetLength(0)).Select(r => source[r, i]);
foreach (var item in ScanLine(line, sample, atLeast))
yield return new Tuple<Point, Point>(new Point(i, item.Item1), new Point(i, item.Item2));
}
}
测试
int[,] board = new int[,] {
{ 0, 1, 1, 0, 0, 0, 0 },
{ 0, 1, 1, 0, 1, 1, 1 },
{ 0, 1, 1, 0, 1, 1, 1 },
{ 0, 1, 1, 0, 1, 1, 1 },
{ 0, 1, 1, 0, 1, 1, 1 },
};
// room for 3-letter words
Console.Write(String.Join(Environment.NewLine, ScanBoard(board, 0, 3)));
返回
({X=3,Y=0}, {X=6,Y=0})
({X=0,Y=0}, {X=0,Y=4})
({X=3,Y=0}, {X=3,Y=4})
关于c# - 查找一行中具有相同值的单元格数,然后存储这些坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39725582/