What is the best way to scroll a 2D sub-array of a 2D array?

If I have a 2D array, it is trivial to scroll through the entire array, row or column using for loops. However, sometimes I need to traverse an arbitrary 2D array.

A good example is Sudoku, in which I could store the entire grid in a 2D array, but then I need to analyze each individual block of 9 squares. Currently, I would do something like the following:

for(i = 0; i < 9; i += 3) {
    for(j = 0; j < 9; j += 3) {
        for(k = 0; k < 3; k++) {
            for(m = 0; m < 3; m++) {
                block[m][k] == grid[j + m][i + k];
            }
        }

        //At this point in each iteration of i/j we will have a 2D array in block 
        //which we can then iterate over using more for loops.
    }
}

Is there a better way to iterate over arbitrary subarrays, especially when they occur in a regular pattern like the one above?

+3
source share
3 answers

The performance in this loop structure will be terrifying. Consider the inner loop:

        for(m = 0; m < 3; m++) {
            block[m][k] == grid[j + m][i + k];
        }

C " ", , block ! , .

grid. i j, grid j . .

, , .

for(j = 0; j < 9; j += 3) {
    for(m = 0; m < 3; m++) {
        for(i = 0; i < 9; i += 3) {
            for(k = 0; k < 3; k++) {
                block[m][k] == grid[j + m][i + k];
            }
        }
        // make sure you access everything so that order doesn't change
        // your program semantics
    }
}
+5

, 9 3x3 . ... , , .

, .

0

, 2D- a[n][m]. q x r, x,y, :

for(int i = x; i < n && i < x + q; ++i)
   for(int j = y; j < m && j < y + r; ++j)
   {
      ///
   }

sudoku

for(int i = 0; i<3; ++i)
    for(int j = 0; j < 3; ++j)
       for(int locali = 0; locali < 3; ++locali)
           for(int localj = 0; localkj <3; ++localj)
               //the locali,localj element of the bigger i,j 3X3 square is 
               a[3*i + locali][3*j+localj]
0

Source: https://habr.com/ru/post/1774690/


All Articles