How to iterate through 2d array starting from some position?

I have to move the piece at a random position X through the whole matrix:

at every new position I compare it to the value at that position (for simplicity the only piece in the matrix is X). While doing this would be easy if X started at 0, but in my case the X piece can start at any position in the matrix, now I first started with this loop:

for(int i = row_x;i<rows;i++)
    for(int j = col_x;j<cols;j++)
        //do something

But doing that will only allow me to visit some fields: vistied fields sample

And I need to visit all the fields highlighted in this picture:required

So what would be the simplest way to fix it?

Upvotes: 2

Views: 877

Answers (3)

Mohamed Benmahdjoub
Mohamed Benmahdjoub

Reputation: 1280

One solution would be to change your 2D array structure into a 1D array and work in 1D (not by an algorithm) then apply this :

init = rows*i+j;

for(int l = init; l<size;i++){
    //do things
}

Upvotes: 2

Urvashi Soni
Urvashi Soni

Reputation: 279

Do not start your inner loop (loop for column iteration from col_x, but from 0th index (first column). This will cover the fields given in required

Upvotes: 0

Flown
Flown

Reputation: 11740

You should check if it is the first iteration of the outer loop:

for(int i = row_x; i < rows; i++)
  for(int j = (i == row_x ? col_x : 0); j < cols; j++)
    //do something

Upvotes: 4

Related Questions