Loop diagonally through two dimensional array

前端 未结 12 1324
刺人心
刺人心 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:58

    This is the same as what leoflower posted here. I've just changed the variable names for better understanding.

    level = denotes the current level of the diagonal that is being printed. Ex:- level = 2 denotes diagonal elements with indices (0,2),(1,1),(2,0)

    currDiagRowIndex = denotes row index of the current diagonal being printed

    currDiagColIndex = denotes columnn index of the current diagonal being printed

    void printMatrixDiagonal(int matrix[][], int endRowIndex, int endColIndex){
        for(int level = 0; level < endColIndex; level++){
            for(int currDiagRowIndex = 0, currDiagColIndex = level; currDiagRowIndex < endRowIndex && currDiagColIndex >= 0 ; currDiagRowIndex++, currDiagColIndex--){
                System.out.print(matrix[currDiagRowIndex][currDiagColIndex] + "  ");
            }
            System.out.println();
        }
    
        for(int level = 1; level < endRowIndex; level++){
            for(int currDiagRowIndex = level, currDiagColIndex = endColIndex-1; currDiagRowIndex < endRowIndex && currDiagColIndex >= 0; currDiagRowIndex++, currDiagColIndex--){
                System.out.print(matrix[currDiagRowIndex][currDiagColIndex]+ "  ");
            }
            System.out.println();
        }
    }
    

    Input:

    1 2 3 4 5 
    6 7 8 9 10
    11 12 13 14 15
    16 17 18 19 20
    21 22 23 24 25
    

    Output:

    1  
    2  6  
    3  7  11  
    4  8  12  16  
    5  9  13  17  21  
    10  14  18  22  
    15  19  23  
    20  24  
    25  
    

提交回复
热议问题