498.js
/** ------------------------------------------------------------------------------
*
* 498. Diagonal Traverse
* Topics: Array, Matrix
* https://leetcode.com/problems/diagonal-traverse/?envType=daily-question&envId=2025-08-25
*
------------------------------------------------------------------------------ */
/**
* @param {number[][]} mat
* @return {number[]}
*/
var findDiagonalOrder = function (mat) {
let result = []
let total = mat[0].length * mat.length - 1
let x = 0
let y = 0
let slope = 1
for (let i = 0; i < total + 1; i++) {
result.push(mat[y][x])
const oldX = x
const oldY = y
if (slope === 0) {
x--
y++
} else {
x++
y--
}
if (y < 0) {
y = 0
slope = 0
}
if (x < 0) {
x = 0
slope = 1
}
if (y === mat.length) {
y--
x++
if (oldX === x) {
x++
}
slope = 1
} else if (x === mat[0].length) {
y++
x--
if (oldY === y) {
y++
}
slope = 0
}
}
return result
}
console.log(
findDiagonalOrder([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]),
)