Finding neighbours in a two-dimensional array

后端 未结 20 1180
忘了有多久
忘了有多久 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:27

    Grid (vector 2D or one dimension... not the problem here)
    X & Y, coordinate of your element (or just pass your vector element by ref...)

    int neighbour(const Grid & g, const size_t & x, const size_t & y) {
        for (int i = -1; i < 2; ++i)
            for (int j = -1; j < 2; ++j)
                if (x + i >= 0 && x + i < g.row && y + j >= 0 && y + j < g.col)
                    //Do some stuff
        return 0;
    }
    

提交回复
热议问题