Loop diagonally through two dimensional array

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

    As Alex mentioned here, you need to look into indices in the loop. The following is how I approached this problem.

    Input:         
    a b c    ----- (0,0) (0,1) (0,2)
    d e f    ----- (1,0) (1,1) (1,2)
    g h i    ----- (2,0) (2,1) (2,2)
    
    Output:
    a        ----- (0,0)
    b d      ----- (0,1) (1,0)
    c e g    ----- (0,2) (1,1) (2,0)
    f h      ----- (1,2) (2,1)
    i        ----- (2,2)
    
    public class PrintDiagonal{
    
        public static void printDR(String[][] matrix, int rows, int cols){
            for(int c=0; c < cols; c++){
                for(int i=0, j=c; i< rows && j>=0;i++,j--){
                    System.out.print(matrix[i][j] +" ");
                 }
                 System.out.println();
            }
    
            for(int r =1; r < rows; r++){
                for(int i =r, j= cols -1; i=0; i++,j--){
                    System.out.print(matrix[i][j] + " ");
                }
                System.out.println();
            }
        }
        public static void main(String[] args){
            String[][] matrix ={
                {"a","b","c"},
                {"d","e","f"},
                {"g","h","i"}
            };
    
            int rows = matrix.length;
            int columns = matrix[0].length; 
            printDR(matrix ,rows, columns);
        }
    }
    

提交回复
热议问题