N

(Leet Code JS)Diagonal Traverse 본문

Leet Code 알고리즘

(Leet Code JS)Diagonal Traverse

naeunchan 2022. 7. 30. 17:41
728x90
반응형

https://leetcode.com/problems/diagonal-traverse/

 

Diagonal Traverse - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

/**
 * @param {number[][]} mat
 * @return {number[]}
 */
var findDiagonalOrder = function(mat) {
    const answer = [];
    const diagonalX = [-1, 1];
    const diagonalY = [1, -1];
    const directX = [0, 1, 1, 0];
    const directY = [1, 0, 0, 1];
    const m = mat.length;
    const n = mat[0].length;
    // if state === 0 : up diagonal, else down diagonal
    let state = 0;
    let x = 0;
    let y = 0;
    
    const checkRange = (x, y) => {
        if(x >= 0 && x < m && y >= 0 && y < n){
            return true;
        }
        
        return false;
    }
    
    while(answer.length < m * n){
        let nx = x + diagonalX[state];
        let ny = y + diagonalY[state];
        
        answer.push(mat[x][y]);
        
        if(checkRange(nx, ny)){
            x = nx;
            y = ny;
        } else{
            nx = x + directX[state];
            ny = y + directY[state];
            
            if(checkRange(nx, ny)){
                x = nx;
                y = ny;
            } else{
                nx = x + directX[state + 2];
                ny = y + directY[state + 2];
                
                x = nx;
                y = ny;
            }
        
            state = state ? 0 : 1;
        }
    }
    
    return answer;
};
728x90
반응형