I looked at the solution written in the article and it honestly looked illegible. So I thought I'd post my explanation here...
The ask of the question is fairly simple. Traverse along each diagonal and save the elements into an array. The extra condition to keep in mind is that we alternate the direction of the traversal for each subsequent diagonal. Even though it seems to make it sound complicated, it really isn't.
Whenever we come across any diagonal traversal related problems, we gotta keep in mind that the sum of the indices across a diagonal are constant and the maximum value of the diagonal sum for a given M * N matrix is (M+N-2). So all we have to do is to traverse the diagonals starting from diagonal sum 0 to (M+N-2).
Now coming to alternating our direction of traversal, we simply have to use a flag that tells the direction in which we should traverse. We toggle this flag after each diagonal is traversed.
class Solution {
public int[] findDiagonalOrder(int[][] matrix) {
//Base conditions
int rowMax = matrix.length;
if(rowMax==0) return new int[0];
int colMax = matrix[0].length;
if(colMax==0) return new int[0];
//Initializing the diagonal sum
int diagonalSum=0;
//flag that tells us if we should traverse top to bottom or bottom to up
boolean startFromTop = false;
int[] op = new int[rowMax*colMax];
int index=0;
while(diagonalSum<rowMax+colMax-1){
if(startFromTop){
//If it's a top to bottom traversal, we max out the column index first and assign the remaining to the row index.
int j = Math.min(colMax-1,diagonalSum);
int i = diagonalSum-j;
while(j>=0 && i<rowMax) op[index++] = matrix[i++][j--];
}else{
//If it's a bottom to top traversal, we max out the row index first and throw the leftovers to the column index.
int i = Math.min(rowMax-1,diagonalSum);
int j = diagonalSum-i;
while(i>=0 && j<colMax) op[index++] = matrix[i--][j++];
}
//Increase the diagonal sum after each traversal and toggle the flag.
diagonalSum++;
startFromTop = !startFromTop;
}
return op;
}
}