Loop diagonally through two dimensional array

前端 未结 12 1317
刺人心
刺人心 2020-12-05 11:52

I wrote the following code to walk half the diagonals of an array:

String[][] b = [a,b,c]
               [d,e,f]
               [g,h,i];  

public void LoopD         


        
12条回答
  •  北海茫月
    2020-12-05 12:16

    This works for non-square arrays. It's simple to understand, but calls min() and max() once per diagonal.

    int ndiags = width +  height - 1;
    System.out.println("---");
    for (int diag = 0; diag < ndiags; diag++) {
        int row_stop = Math.max(0,  diag -  width + 1);
        int row_start = Math.min(diag, height - 1);
        for (int row = row_start; row >= row_stop; row--) {
            // on a given diagonal row + col = constant "diag"
            // diag labels the diagonal number
            int col = diag - row;
            System.out.println(col + "," + row);
            relax(col, row);
        }
        System.out.println("---");
    }
    

    Here's output for width=3, height=3

    ---
    0,0
    ---
    0,1
    1,0
    ---
    0,2
    1,1
    2,0
    ---
    1,2
    2,1
    ---
    2,2
    ---
    

    width=3, height=2

    ---
    0,0
    ---
    0,1
    1,0
    ---
    1,1
    2,0
    ---
    2,1
    ---
    

    width = 2, height = 3

    ---
    0,0
    ---
    0,1
    1,0
    ---
    0,2
    1,1
    ---
    1,2
    ---
    

提交回复
热议问题