Traverse Matrix in Diagonal strips

前端 未结 16 1842
暖寄归人
暖寄归人 2020-11-28 02:55

I thought this problem had a trivial solution, couple of for loops and some fancy counters, but apparently it is rather more complicated.

So my question is, how woul

16条回答
  •  执笔经年
    2020-11-28 03:44

    Let's take a look how matrix elements are indexed.

    (0,0)   (0,1)   (0,2)   (0,3)   (0,4)  
    (1,0)   (1,1)   (1,2)   (1,3)   (1,4)  
    (2,0)   (2,1)   (2,2)   (2,3)   (2,4)  
    

    Now, let's take a look at the stripes:

    Stripe 1: (0,0)
    Stripe 2: (0,1)    (1,0)  
    Stripe 3: (0,2)    (1,1)    (2,0)
    Stripe 4: (0,3)    (1,2)    (2,1)
    Stripe 5: (0,4)    (1,3)    (2,2)
    Stripe 6: (1,4)    (2,3)
    Stripe 7: (2,4)
    

    If you take a closer look, you'll notice one thing. The sum of indexes of each matrix element in each stripe is constant. So, here's the code that does this.

    public static void printSecondaryDiagonalOrder(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        int maxSum = rows + cols - 2;
    
        for (int sum = 0; sum <= maxSum; sum++) {
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < cols; j++) {
                    if (i + j - sum == 0) {
                        System.out.print(matrix[i][j] + "\t");
                    }
                }
            }
            System.out.println();
        }
    }
    

    It's not the fastest algorithm out there (does(rows * cols * (rows+cols-2)) operations), but the logic behind it is quite simple.

提交回复
热议问题