I can't seem to figure out an elegant way to do this, but I know I have seen it in the past. I just don't know what to search for.

I am given the row and column indices, r and c of a 2-D matrix. I want to be able to traverse the 4 neighbors. If the element is at a corner, it will only have 2 neighbors. If the element is at the boundary, but not a corner, it will have 3 neighbors. If it's interior it will have 4 neighbors.

So I want to traverse (r+1,c), (r-1,c), (r,c+1), (r,c-1) and perform the bounds check r >= 0 && r < num_rows and c >= 0 && c < num_cols simultaneously in a double nested for loop.

The only thing I was able to come up with is this:

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]]


The particularly elegant one I remember seeing did something with a max function and didn't use the adds array that I have.

0 Answers