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
Solutions would be much easier if we break it down into 2 sub-problems:
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("");
}