简体   繁体   中英

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?

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

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
}

不要启动内循环(循环从col_x列迭代,但是从第0指数(第一列),这将涵盖中给出的领域需要

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM