查找共享相同值的行中的单元格数,然后存储这些坐标

时间:2016-09-27 13:11:05

标签: c# .net arrays multidimensional-array

所以我是初学者,我正在构建一个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的模式。有人知道最好的解决方法吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

您必须扫描2D阵列的线和列。为了表明这个想法,我选择了

 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})