c# - 查找一行中具有相同值的单元格数,然后存储这些坐标

标签 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 的模式。有人知道解决这个问题的最佳方法吗?

谢谢!

最佳答案

您必须扫描二维数组的行和列。为了展示这个想法,我选择了

 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/

相关文章:

.net - Azure 上的 Sentry 发布跟踪

php - 如何简化我的数组代码

c# - Process.Start() 中的错误——系统找不到指定的文件

c# - 判断System.Net.Mail.SmtpClient.Send结果

c# - 在 WPF C# TreeView 中获取子节点的父节点

php - YII2平面阵列

c++ - 如何操纵包含2D数组的结构的数组

c# - 无法从用法中推断出方法的类型参数

c# - 在 LINQ 查询期间提供用户反馈

c# - UWP AcrylicBrush 向后兼容最低版本 14393(周年更新)