c# - 在二维矩阵中查找相邻元素

标签 c# algorithm matrix

我有一个 m *n 阶的二维矩阵

00 01 02 03 ....0n
10 11 12 13 ....1n
20 21 22 23 ....2n
..
m0 m1 m2  m3 ...mn

据此,给定一个元素,我需要编写一个返回其相邻元素的方法。 相邻元素水平、垂直或对角线相邻。

例如01的相邻元素为00,02,10,11,12 00 的相邻元素是 01 ,10,11 11的相邻元素是00,01,02,10,12,20,21,22

谁能帮我用一种乐观的算法来解决这个问题?

最佳答案

public static IEnumerable<T> AdjacentElements<T>(T[,] arr, int row, int column)
{
    int rows = arr.GetLength(0);
    int columns = arr.GetLength(1);

    for (int j = row - 1; j <= row + 1; j++)
        for (int i = column - 1; i <= column + 1; i++)
            if (i >= 0 && j >= 0 && i < columns && j < rows && !(j == row && i == column))
                yield return arr[j, i];
}

...

var arr = new[,] { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} };

var results = AdjacentElements(arr, 1, 3);

foreach(var result in results) 
    Console.WriteLine(result)

这产生了答案: 3个 4个 7 11 12 (与 8 相邻的元素)。

关于c# - 在二维矩阵中查找相邻元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12471463/

相关文章:

c++ - 密集对称矩阵的特征有效类型

arrays - Swift 中的任意矩阵或数组大小

c# - LINQ 查询以从多个列表中按条件过滤项目

algorithm - 添加新点时如何避免重复线性回归过程

algorithm - 给定一个未排序的整数数组 A,返回一个数组 B,其中 B[i] 是 A[j] 的数量,使得 A[i] > A[j] 而 i < j

C++ 使用带字符串的标准算法,带 isdigit 的 count_if,函数转换

algorithm - 从大型文本文件快速形成矩阵

c# - 使用 .net 4.6.2 的异步方法后 OperationContext 为 null

javascript - 使用 javascript ...cefsharp 从 Form1 (winform c#) 打开 Form2

c# - 在 UWP 中使用 DataTriggerBehavior 更改 ContentTemplate