Loop diagonally through two dimensional array

前端 未结 12 1314
刺人心
刺人心 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 11:59

    This is how:

    int [][]mat = { {1,2,3},
                    {4,5,6},
                    {7,8,9},
    };
    
    int N=3;
    
    for (int s=0; s-1; i--) {
            System.out.print(mat[i][s-i] + " ");
        }
        System.out.println();
    }
    
    for (int s=1; s=s; i--) {
            System.out.print(mat[i][s+N-1-i] + " ");
        }
        System.out.println();
    }
    

    The first loop prints the diagonals beginning from first column, the second loop prints the remaining diagonals (beginning from bottom row).

    Output:

    1 
    4 2 
    7 5 3 
    8 6 
    9 
    

提交回复
热议问题