Created
August 25, 2025 19:09
-
-
Save tatsuyax25/f878d0d9ab125b38fa8fce56e2752f8b to your computer and use it in GitHub Desktop.
Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[][]} mat | |
* @return {number[]} | |
*/ | |
var findDiagonalOrder = function(mat) { | |
// Edge case: empty matrix | |
if (!mat || mat.length === 0 || mat[0].length === 0) return []; | |
const m = mat.length; // number of rows | |
const n = mat[0].length; // number of columns | |
const result = []; | |
let row = 0, col = 0; | |
let directionUp = true; // true = moving up-right, false = down-left | |
// We need to collect m * n elements | |
while (result.length < m * n) { | |
result.push(mat[row][col]); | |
if (directionUp) { | |
// Moving up-right | |
if (col === n - 1) { | |
// Hit right boundary, move down | |
row++; | |
directionUp = false; | |
} else if (row === 0) { | |
// Hit top boundary, move right | |
col++; | |
directionUp = false; | |
} else { | |
// Normal up-right move | |
row--; | |
col++; | |
} | |
} else { | |
// Moving down-left | |
if (row === m - 1) { | |
// Hit bottom boundary, move right | |
col++; | |
directionUp = true; | |
} else if (col === 0) { | |
// Hit left boundary, move down | |
row++; | |
directionUp = true; | |
} else { | |
// Normal down-left move | |
row++; | |
col--; | |
} | |
} | |
} | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment