Diagonal Traverse
Description
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.
Example:
Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]Output: [1,2,4,7,5,3,6,8,9]
Explanation:
Note:
The total number of elements of the given matrix will not exceed 10,000.
Solution(javascript)
/*
* @lc app=leetcode id=498 lang=javascript
*
* [498] Diagonal Traverse
*/
// @lc code=start
/**
* @param {number[][]} matrix
* @return {number[]}
*/
const findDiagonalOrder = function (matrix) {
const result = []
let i = 0
let j = 0
let up = true
while (i < matrix.length && j < matrix[i].length) {
result.push(matrix[i][j])
if (up) {
if (j === matrix[i].length - 1) {
up = false
i++
} else if (i === 0) {
j++
up = false
} else {
i--
j++
}
} else if (i === matrix.length - 1) {
up = true
j++
} else if (j === 0) {
up = true
i++
} else {
i++
j--
}
}
return result
}
// @lc code=end