|
| 1 | +# [498. Diagonal Traverse](https://leetcode.com/problems/diagonal-traverse) |
| 2 | + |
| 3 | +## Description |
| 4 | + |
| 5 | +<div class="elfjS" data-track-load="description_content"><p>Given an <code>m x n</code> matrix <code>mat</code>, return <em>an array of all the elements of the array in a diagonal order</em>.</p> |
| 6 | + |
| 7 | +<p> </p> |
| 8 | +<p><strong class="example">Example 1:</strong></p> |
| 9 | +<img alt="" src="https://assets.leetcode.com/uploads/2021/04/10/diag1-grid.jpg" style="width: 334px; height: 334px;"> |
| 10 | +<pre><strong>Input:</strong> mat = [[1,2,3],[4,5,6],[7,8,9]] |
| 11 | +<strong>Output:</strong> [1,2,4,7,5,3,6,8,9] |
| 12 | +</pre> |
| 13 | + |
| 14 | +<p><strong class="example">Example 2:</strong></p> |
| 15 | + |
| 16 | +<pre><strong>Input:</strong> mat = [[1,2],[3,4]] |
| 17 | +<strong>Output:</strong> [1,2,3,4] |
| 18 | +</pre> |
| 19 | + |
| 20 | +<p> </p> |
| 21 | +<p><strong>Constraints:</strong></p> |
| 22 | + |
| 23 | +<ul> |
| 24 | + <li><code>m == mat.length</code></li> |
| 25 | + <li><code>n == mat[i].length</code></li> |
| 26 | + <li><code>1 <= m, n <= 10<sup>4</sup></code></li> |
| 27 | + <li><code>1 <= m * n <= 10<sup>4</sup></code></li> |
| 28 | + <li><code>-10<sup>5</sup> <= mat[i][j] <= 10<sup>5</sup></code></li> |
| 29 | +</ul> |
| 30 | +</div> |
| 31 | + |
| 32 | +<p> </p> |
| 33 | + |
| 34 | +## Solutions |
| 35 | + |
| 36 | +**Solution: `Simulation`** |
| 37 | + |
| 38 | +- Time complexity: <em>O(mn)</em> |
| 39 | +- Space complexity: <em>O(mn)</em> |
| 40 | + |
| 41 | +<p> </p> |
| 42 | + |
| 43 | +### **JavaScript** |
| 44 | + |
| 45 | +```js |
| 46 | +/** |
| 47 | + * @param {number[][]} mat |
| 48 | + * @return {number[]} |
| 49 | + */ |
| 50 | +const findDiagonalOrder = function (mat) { |
| 51 | + const m = mat.length; |
| 52 | + const n = mat[0].length; |
| 53 | + const result = []; |
| 54 | + let row = 0; |
| 55 | + let col = 0; |
| 56 | + let direction = 1; |
| 57 | + |
| 58 | + for (let index = 0; index < m * n; index++) { |
| 59 | + let nextRow = row - direction; |
| 60 | + let nextCol = col + direction; |
| 61 | + |
| 62 | + if (nextCol < 0) { |
| 63 | + nextCol = nextRow > m - 1 ? 1 : 0; |
| 64 | + nextRow = Math.min(m - 1, nextRow); |
| 65 | + direction *= -1; |
| 66 | + } else if (nextCol >= n) { |
| 67 | + nextCol = n - 1; |
| 68 | + nextRow = row + 1; |
| 69 | + direction *= -1; |
| 70 | + } else if (nextRow < 0) { |
| 71 | + nextRow = 0; |
| 72 | + direction *= -1; |
| 73 | + } else if (nextRow >= m) { |
| 74 | + nextRow = m - 1; |
| 75 | + nextCol = col + 1; |
| 76 | + direction *= -1; |
| 77 | + } |
| 78 | + |
| 79 | + result[index] = mat[row][col]; |
| 80 | + row = nextRow; |
| 81 | + col = nextCol; |
| 82 | + } |
| 83 | + |
| 84 | + return result; |
| 85 | +}; |
| 86 | +``` |
0 commit comments