【问题标题】:Need working C# code to find neighbors of an element in a 2-dimentional array需要工作 C# 代码来查找二维数组中元素的邻居
【发布时间】:2011-04-12 19:30:05
【问题描述】:

说 12 行 10 列的数组

int[,] array = new int[12,10];

我选择 0,0 它必须返回 0,0 的所有邻居 这将是

0,1
1,1
1,0

说我想要 2,3 的邻居,它必须返回一个邻居数组

1,2
1,3
1,4
2,2
2,4
3,1
3,2
3,3

【问题讨论】:

  • 这不是这个网站的真正运作方式。你真的尝试过吗?
  • 另外,您还没有接受任何关于您之前发布的问题的答案(单击复选标记)

标签: c# arrays multidimensional-array


【解决方案1】:
element [x, y]

neighbor1 = x + 1, y;
neighbor2 = x - 1, y;
neighbor3 = x, y + 1;
neighbor4 = x, y - 1;
neighbor5 = x + 1, y + 1;
neighbor6 = x + 1, y - 1;
neighbor7 = x - 1, y + 1;
neighbor8 = x - 1, y - 1;

显然,您需要检查这些元素坐标是否存在,以防万一元素位于矩阵的“边界”中。难的?我说不。

【讨论】:

    【解决方案2】:

    脑残且表现不佳,但说明性和快速性:

            int[,] array = new int[12,10];
    
            int refx=0, refy=10;
    
            var neighbours = from x in Enumerable.Range(0,array.GetLength(0)).Where(x => Math.Abs(x - refx)<=1)
                             from y in Enumerable.Range(0,array.GetLength(1)).Where(y => Math.Abs(y - refy)<=1)
                             select new {x,y};
    
            neighbours.ToList().ForEach(Console.WriteLine);
    

    或者

            neighbours = from x in Enumerable.Range(refx-1, 3)
                         from y in Enumerable.Range(refy-1, 3)
                         where x>=0 && y>=0 && x<array.GetLength(0) && y<array.GetLength(1)
                         select new {x,y};
    
            neighbours.ToList().ForEach(Console.WriteLine);
    

    【讨论】:

    猜你喜欢
    • 2017-10-04
    • 2010-10-13
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    相关资源
    最近更新 更多