如何在C#中的矩阵中获取单元的邻居

时间:2017-12-25 19:35:58

标签: c# arrays

我尝试使用以下方法在2D数组中使用行索引和列索引来打印任何给定单元格的邻居:

public static List<int[,]> getAUVNieghborsCells(int [,] grid, int row, int col)
{

    List<int[,]> n = new List<int[,]>();

    //define boundaries
    int rowLen = Math.Min(row + 1, grid.GetLength(0) - 1),
        colLen = Math.Min(col + 1, grid.GetLength(1) - 1),
        rowIdx = Math.Max(0, row - 1),
        colIdx = Math.Max(0, col - 1);

    for (int i = rowIdx; i <= rowLen; i++)
    {
        for (int j = colIdx; j <= colLen; j++)
        {
            //if it is our given index, continue
            if (i == row && j == col)
                continue;

            int[,] temp = new int[1, 2];

            temp[0, 0] = i;
            temp[0, 1] = j;

            n.Add(temp);
        }
    }

  return n;
}

我发送(4,0)但我得到了:

  

|(4,0)||(4,1)||(5,1)||(6,0)||(6,1)|

这是错误的,因为它们是(5,0)和(4,0)的邻居。问题在哪里?

2 个答案:

答案 0 :(得分:0)

以下代码是否符合您的需求?

Int32 targX = 4;
Int32 targY = 0;
Point targ = new Point(targX, targY);

List<Point> neighbours = (from x in Enumerable.Range(targX - 1, 3)
                          from y in Enumerable.Range(targY - 1, 3)
                          where (x >= 0) && (x < grid.GetLength(0)) && (y >= 0) && (y < grid.GetLength(1))
                          select new Point(x, y))
                         .Where(p => p != targ).ToList();

演示代码here

答案 1 :(得分:0)

对我来说,你的代码可以很好地生成(3,0);(3,1);(4,1);(5,0);(5,1)用于(4,0)输入。 我也写了自己的东西,得到了相同的输出。

private static List<int[,]> getNeigbores(int[,] matrix, int row, int column)
    {
        List<int[,]> result = new List<int[,]>();
        int rowMinimum = row - 1 < 0 ? row : row - 1;
        int rowMaximum = row + 1 > matrix.GetLength(0) ? row : row + 1;
        int columnMinimum = column - 1 < 0 ? column : column - 1;
        int columnMaximum = column + 1 > matrix.GetLength(1) ? column : column + 1;
        for (int i = rowMinimum; i <= rowMaximum; i++)
            for (int j = columnMinimum; j <= columnMaximum; j++)
                if (i != row || j != column)
                    result.Add(new int[1, 2] { { i, j } });
        return result;
    }