所以我是一个初学者,我正在构建一个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>
分别表示1D和2D数组中的范围。当然,Tuple<Point, Point>
不是一个好的选择,您可能希望将其更改为一些量身定制的类。
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})