Verbose Java Solution with all 6 cases considered


  • 0
    public int[] findDiagonalOrder(int[][] matrix) {
        int m = matrix.length;
        if(m==0)
            return new int[0];
        int n = matrix[0].length;
        int[] res = new int[m*n];
        int idx=0, i=0, j=0;
        int dir = 1;
        while(idx<m*n) {
            if(dir==1) {
                res[idx] = matrix[i][j];
                if(i-1<0 && j+1==n) {
                    i++;
                    dir=0;
                } else if(i-1<0) {
                    j++;
                    dir=0;
                } else if(j+1==n) {
                    i++;
                    dir=0;
                } else {
                    i--;
                    j++;
                }
            } else {
                res[idx] = matrix[i][j];
                if(j-1<0 && i+1==m) {
                    j++;
                    dir=1;
                } else if(j-1<0) {
                    i++;
                    dir=1;
                } else if(i+1==m) {
                    j++;
                    dir=1;
                } else {
                    i++;
                    j--;
                }
            }
            idx++;
        }
        return res;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.