Loop diagonally through two dimensional array

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

    I wrote the following code. The key is to exhaust all of the diagonals that start at the top and then move onto the diagonals that start on the sides. I included a method that combines the two angles to traverse diagonals Northwest - Southeast and Northeast - Southwest and stand alone methods for traversing the respective angles.

    public static void main(String[] args){
        int[][] m = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
        printDiagonals(m, DiagonalDirection.NEtoSW, new DiagonalVisitor() {     
            public void visit(int x, int y, int[][] m) {
                System.out.println(m[x][y]);
            }
        });
    }
    
    public enum DiagonalDirection{
        NWToSE,
        NEtoSW
    }
    
    private static abstract class DiagonalVisitor{
        public abstract void visit(int x, int y, int[][] m);
    }
    
    public static void printDiagonals(int[][] m, DiagonalDirection d, DiagonalVisitor visitor){
    
        int xStart = d==DiagonalDirection.NEtoSW ? 0 : m.length-1;
        int yStart = 1;
    
    
        while(true){
            int xLoop, yLoop;
            if(xStart>=0 && xStart=0)&&yLoop=0 && yLoop=0){
                xLoop = xStart;
                yLoop = 0;
                xStart--;
            }else if(yStart

提交回复
热议问题