找到一个二维矩阵相邻的元素 [英] Find adjacent elements in a 2D matrix

查看:334
本文介绍了找到一个二维矩阵相邻的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为m * n的2维矩阵

  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

可以有一个人帮助我以乐观的算法来解决这个问题?

解决方案

 公共静态的IEnumerable< T> AdjacentElements< T>(T [,]编曲,诠释行,诠释列)
{
    int的行数= arr.GetLength(0);
    int的列= arr.GetLength(1);

    对于(INT J =行 -  1; J< =行+ 1; J ++)
        的for(int i =列 -  1; I< =列+ 1;我++)
            如果(I> = 0&功放;&放大器; J> = 0&功放;&安培; I<列和放大器;&放大器; J<行和放大器;&安培;!(j ==行和放大器;&安培;我==列))
                收益回报ARR [J,I]
}

...

变种改编=新[,] {{1,2,3,4},{5,6,7,8},{9,10,11,12}};

VAR的结果= AdjacentElements(ARR,1,3);

的foreach(VAR导致的结果)
    Console.WriteLine(结果)
 

这得到了答案: 3 4 7 11 12 (邻近8的元素)。

I have a 2 dimensional matrix of order m *n

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

From this, given an element , i need to write a method that returns its adjacent elements. Adjacent elements are either horizontally, vertically, or diagonally adjacent.

For example, adjacent element of 01 is 00,02,10,11,12 adjacent element of 00 is 01 ,10,11 adjacent element of 11 is 00,01,02,10,12,20,21,22

Can some one help me with an optimistic algorithm to solve this?

解决方案

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)

This yields the answer: 3 4 7 11 12 (the elements adjacent to the 8).

这篇关于找到一个二维矩阵相邻的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆