250x250
반응형
Notice
Recent Posts
Recent Comments
Link
N
(Leet Code JS)Diagonal Traverse 본문
728x90
반응형
https://leetcode.com/problems/diagonal-traverse/
/**
* @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
반응형
'Leet Code 알고리즘' 카테고리의 다른 글
(Leet Code JS)Capacity To Ship Packages Within D Days (0) | 2023.02.25 |
---|---|
(Leet Code JS)Longest Increasing Subsequence (0) | 2022.08.20 |
(Leet Code JS)Game of Life (0) | 2022.07.30 |
(Leet Code JS)Candy (0) | 2022.07.10 |
(Leet Code JS)Wiggle Subsequence (0) | 2022.07.09 |