Loop diagonally through two dimensional array

前端 未结 12 1316
刺人心
刺人心 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<rows && j>=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);
        }
    }
    
    0 讨论(0)
  • 2020-12-05 12:09

    Solutions would be much easier if we break it down into 2 sub-problems:

    1. Figure out the start of each diagonal.
    2. Given the starting indices of a diagonal, print the diagonal.

      public void printMatrixDiagonals(int[][] matrix) {
      
          int c = 0;
          int count = matrix.length + matrix[0].length -1;
          int i = 0, j = 0;
          //There can be at most  m + n -1 diagonals to be printed
          while (c < count) {
              //Start printing diagonals from i and j
              printDiagonal(i, j, matrix);
              if (i < matrix.length -1) {
                  //We increment row index until we reach the max number of rows
                  i++;
              } else if (j < matrix[0].length - 1) {
                  //We are at maximum index of row; so its time to increment col index
                  //We increment column index until we reach the max number of columns
                  j++;
              }
              c++;
          }
      }
      

    Print Diagonal: Notice that every time we start printing each diagonal, the index of row should be decremented and the index of column should be incremented. So given the starting indices of each diagonal, we can print the diagonal as follows:

    private void printDiagonal(int i, int j, int[][] m) {
        while (i >=0 && j< m[0].length ) {
            System.out.print(m[i][j] + " ");
            i--;
            j++;
        }
        System.out.println("");
    }
    
    0 讨论(0)
  • 2020-12-05 12:15
        String ar[][]={{"a","b","c"},{"d","e","f"},{"g","h","i"}};
        int size1=ar.length-1, size2=ar.length;
    
        for(int i=0; i<ar.length; i++)
        {   
            String a="";        
            for(int j=0, x=ar.length-1-i; j<ar.length-i; j++, x--)
            {
                if((j+x)==size1)
                a=a+ar[x][j];
            }
            size1--;
    
            System.out.println(a);
            a="";
            for(int j=i+1, x=ar.length-1; j<ar.length; j++, x--)
            {
                if((j+x)==size2)
                a=a+ar[x][j];
            }
            System.out.println(a);
            size2++;
        }
    

    OUTPUT

    gec hf db i a

    0 讨论(0)
  • 2020-12-05 12:16

    This works for non-square arrays. It's simple to understand, but calls min() and max() once per diagonal.

    int ndiags = width +  height - 1;
    System.out.println("---");
    for (int diag = 0; diag < ndiags; diag++) {
        int row_stop = Math.max(0,  diag -  width + 1);
        int row_start = Math.min(diag, height - 1);
        for (int row = row_start; row >= row_stop; row--) {
            // on a given diagonal row + col = constant "diag"
            // diag labels the diagonal number
            int col = diag - row;
            System.out.println(col + "," + row);
            relax(col, row);
        }
        System.out.println("---");
    }
    

    Here's output for width=3, height=3

    ---
    0,0
    ---
    0,1
    1,0
    ---
    0,2
    1,1
    2,0
    ---
    1,2
    2,1
    ---
    2,2
    ---
    

    width=3, height=2

    ---
    0,0
    ---
    0,1
    1,0
    ---
    1,1
    2,0
    ---
    2,1
    ---
    

    width = 2, height = 3

    ---
    0,0
    ---
    0,1
    1,0
    ---
    0,2
    1,1
    ---
    1,2
    ---
    
    0 讨论(0)
  • 2020-12-05 12:18

    This is very intuitive way to print diagonal matrix in while loop .

    generalize the problem as whole rather than two part and optimized in terms of space complexity .

    package algorithm;
    
    public class printDiagonaly
    {
        public static void main(String[] args)
        {
            int[][] a = new int[][]{{1, 2, 3, 4, 5},
                    {6, 7, 8, 9, 10},
                    {11, 12, 13, 14, 15},
                    {16, 17, 18, 19, 20}};
    
            int lr = 0;
            int lc = -1;
            int fr = -1;
            int fc = 0;
            int row = a.length - 1;
            int col = a[0].length - 1;
    
            while (lc < col || fc < col || fr < row || lr < row)
            {
                if (fr < row)
                {
                    fr++;
                }
                else
                {
                    fc++;
                }
    
                if (lc < col)
                {
                    lc++;
                }
                else
                {
                    lr++;
                }
    
                int tfr = fr;
                int tlr = lr;
                int tlc = lc;
                int tfc = fc;
    
                while (tfr >= tlr && tfc <= tlc)
                {
    
                    System.out.print(a[tfr][tfc] + " ");
                    tfr--;
                    tfc++;
                }
                System.out.println("\n");
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-05 12:19

    Just help yourself, have a look at the indices you need to loop through:

    #1 (0,0)               -> a
    #2 (1,0)  (0,1)        -> bd
    #3 (2,0)  (1,1)  (0,2) -> gec
    #4 (2,1)  (1,2)        -> hf
    #5 (2,2)               -> i
    

    Look at the change of the indices in each iteration and create your algorithm. Not so difficult, so do your homework yourself ;)

    0 讨论(0)
提交回复
热议问题