遍历矩阵元素的邻居并检查范围的正确的循环代码是什么?

时间:2019-06-02 04:24:23

标签: for-loop matrix language-agnostic

我似乎无法找到一种优雅的方式来做到这一点,但是我知道我过去已经看过它。我只是不知道要搜索什么。

我得到了二维矩阵的行和列索引rc。我希望能够遍历这四个邻居。如果元素在一个角上,则将只有2个邻居。如果元素在边界而不是拐角处,则它将具有3个邻居。如果是内部,它将有4个邻居。

因此,我想遍历(r+1,c)(r-1,c)(r,c+1)(r,c-1),并在同一时间执行边界检查r >= 0 && r < num_rowsc >= 0 && c < num_cols双重嵌套的循环。

我唯一能想到的是:

vector<vector<int>> adds{{0,1},{1,0},{-1,0},{0,-1}}

for(int i = 0; i < adds.size(); i++)
{
  //do bounds checking with r + adds[i][0] and c + adds[i][1]
  //do something with matrix[r + adds[i][0]][c + adds[i][1]]

}

我记得看到的一个特别优雅的函数使用max函数执行某些操作,并且没有使用我拥有的adds数组。

1 个答案:

答案 0 :(得分:0)

复数! :D

Complex i = {0, 1};

int neighbours[4];
// Multiplying by i to rotate 90 degrees
for (int i = 0, Complex offset = {1,0}; i < 4; ++i, offset *= i) {
  if (x + offset.re >= width or x + offset.re < 0 or y + offset.im >= length) 
    neighbours[i] = nullptr; // Some known invalid value
  else
    neighbours[i] = arr[x + offset.re][y + offset.im];
}

这是我的implementations之一。

一件很酷的事情是,如果更改乘数表示的角度({cos(phi), sin(phi)}),则可以得到矩阵周围的六边形单元!您甚至可以更改它们与主单元格的距离或整个对象的旋转。

image i can't post yet