Accepted Javascript solution


  • 0
    R

    Open to comments for improvement.

    function findDiagonalOrder(matrix, row = 0, col = 0, output = []) {
        if (!matrix || !matrix.length) {
            return output;
        }
    
        let up = true,
            rowLgth = matrix.length,
            colLgth = matrix[ 0 ].length,
            lgth = rowLgth * colLgth;
    
        while (output.length < lgth) {
            output.push(matrix[ row ][ col ]);
    
            if (up) {
                if (col + 1 >= colLgth) {
                    row += 1;
                    up = false;
                } else if (row - 1 < 0) {
                    col += 1;
                    up = false;
                } else {
                    row -= 1;
                    col += 1;
                }
            } else {
                if (row + 1 >= rowLgth) {
                    col += 1;
                    up = true;
                } else if (col - 1 < 0) {
                    row += 1;
                    up = true;
                } else {
                    row += 1;
                    col -= 1;
                }
            }
        }
    
        return output;
    }
    

Log in to reply
 

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