|
| 1 | +/** |
| 2 | + * 2624. Snail Traversal |
| 3 | + * https://leetcode.com/problems/snail-traversal/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Write code that enhances all arrays such that you can call the snail(rowsCount, |
| 7 | + * colsCount) method that transforms the 1D array into a 2D array organised in the |
| 8 | + * pattern known as snail traversal order. Invalid input values should output an |
| 9 | + * empty array. If rowsCount * colsCount !== nums.length, the input is considered invalid. |
| 10 | + * |
| 11 | + * Snail traversal order starts at the top left cell with the first value of the |
| 12 | + * current array. It then moves through the entire first column from top to bottom, |
| 13 | + * followed by moving to the next column on the right and traversing it from bottom |
| 14 | + * to top. This pattern continues, alternating the direction of traversal with each |
| 15 | + * column, until the entire current array is covered. For example, when given the |
| 16 | + * input array [19, 10, 3, 7, 9, 8, 5, 2, 1, 17, 16, 14, 12, 18, 6, 13, 11, 20, 4, 15] |
| 17 | + * with rowsCount = 5 and colsCount = 4, the desired output matrix is shown below. |
| 18 | + * Note that iterating the matrix following the arrows corresponds to the order |
| 19 | + * of numbers in the original array. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number} rowsCount |
| 24 | + * @param {number} colsCount |
| 25 | + * @return {Array<Array<number>>} |
| 26 | + */ |
| 27 | +Array.prototype.snail = function(rowsCount, colsCount) { |
| 28 | + if (rowsCount * colsCount !== this.length) return []; |
| 29 | + |
| 30 | + const result = Array.from({ length: rowsCount }, () => []); |
| 31 | + let index = 0; |
| 32 | + |
| 33 | + for (let col = 0; col < colsCount; col++) { |
| 34 | + if (col % 2 === 0) { |
| 35 | + for (let row = 0; row < rowsCount; row++) { |
| 36 | + result[row][col] = this[index++]; |
| 37 | + } |
| 38 | + } else { |
| 39 | + for (let row = rowsCount - 1; row >= 0; row--) { |
| 40 | + result[row][col] = this[index++]; |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + return result; |
| 46 | +} |
0 commit comments