Finding neighbours in a two-dimensional array

后端 未结 20 1195
忘了有多久
忘了有多久 2020-11-30 02:02

Is there an easy way of finding the neighbours (that is, the eight elements around an element) of an element in a two-dimensional array? Short of just subtracting and adding

20条回答
  •  情歌与酒
    2020-11-30 02:33

    Rows and Cols are total number of rows and cols

    Define a CellIndex struct or class. Or you can just return the actual values instead of the indexes.

    public List GetNeighbors(int rowIndex, int colIndex)
    {
    var rowIndexes = (new int[] { rowIndex - 1, rowIndex, rowIndex + 1 }).Where(n => n >= 0 && n < Rows);
    
    var colIndexes = (new int[] { colIndex - 1, colIndex, colIndex + 1 }).Where(n => n >= 0 && n < Cols);
    
    return (from row in rowIndexes from col in colIndexes where row != rowIndex || col != colIndex select new CellIndex { Row = row, Col = col }).ToList();
    }
    

提交回复
热议问题