Print All Diagonals of a given matrix

Objective: Given two dimensional matrix, write an algorithm to print all the diagonals of matrix.

Example:
Print All Diagonals of Matix 2

Approach:

We will solve this problem in two parts. first half of diagonals and second half of diagonals.

See the code for more understanding, its self explanatory.

Complete Code:

Output:

1
5 2
9 6 3
13 10 7 4
14 11 8
15 12
16

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

  • zsalabc

    How about this?

    public static void print(int[][] a) {
    int startColumn = 0;
    int lastRow = a.length-1;
    for (int r = 0; r < a.length || startColumn = a.length) {
    dr = lastRow;
    startColumn++;
    }
    for (int c = startColumn; c
    = 0; c++) {
    System.out.print(” “+a[dr–][c][/c]);
    }
    System.out.println();
    }
    }

  • Prateek Gupta

    Simple Solution:
    public static void print(int[][] a) {
    int m=a.length;
    int n=a[0].length;
    for(int i=0;i=m-1)x=m-1;
    int y=i-x;
    while(x>=0 && y<n && x=0){
    System.out.print(a[x][y]+” “);
    x–;y++;
    }
    System.out.println();
    }
    }

  • HectorGuo

    There is an another solution that just loop the matrix (don’t need to consider half and half):

    function diagonalPrint(matrix) {
    const len = matrix.length;
    let output = {};

    // sum of index in every diagonal is the same
    // 0 – 00
    // 1 – 01 10
    // 2 – 02 11 20
    // 3 – 03 12 21 30
    for(let i = 0; i < len; i++) {
    for(let j = 0; j < len; j++) {
    if(!output[i+j]) {
    output[i+j] = [];
    }
    output[i+j].push(matrix[j][i]); // loop by column, matrix[i][j] – loop by row
    }
    }

    return output;
    }

    // output
    {
    0: [1],
    1: [5, 2],
    2: [9,6, 3],

    }

%d bloggers like this: