Loop diagonally through two dimensional array

前端 未结 12 1328
刺人心
刺人心 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: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("");
    }
    

提交回复
热议问题