# What is the correct for loop code that traverses the neighbors of a matrix element and checks bounds?

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++)
{
The particularly elegant one I remember seeing did something with a max function and didn't use the `adds` array that I have.