|
| 1 | +/** |
| 2 | + * 1138. Alphabet Board Path |
| 3 | + * https://leetcode.com/problems/alphabet-board-path/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * On an alphabet board, we start at position (0, 0), corresponding to character board[0][0]. |
| 7 | + * |
| 8 | + * Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"], as shown in the diagram below. |
| 9 | + * |
| 10 | + * We may make the following moves: |
| 11 | + * - 'U' moves our position up one row, if the position exists on the board; |
| 12 | + * - 'D' moves our position down one row, if the position exists on the board; |
| 13 | + * - 'L' moves our position left one column, if the position exists on the board; |
| 14 | + * - 'R' moves our position right one column, if the position exists on the board; |
| 15 | + * - '!' adds the character board[r][c] at our current position (r, c) to the answer. |
| 16 | + * |
| 17 | + * (Here, the only positions that exist on the board are positions with letters on them.) |
| 18 | + * |
| 19 | + * Return a sequence of moves that makes our answer equal to target in the minimum number of |
| 20 | + * moves. You may return any path that does so. |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * @param {string} target |
| 25 | + * @return {string} |
| 26 | + */ |
| 27 | +var alphabetBoardPath = function(target) { |
| 28 | + let path = ''; |
| 29 | + let row = 0; |
| 30 | + let col = 0; |
| 31 | + |
| 32 | + for (const char of target) { |
| 33 | + const code = char.charCodeAt(0) - 97; |
| 34 | + const targetRow = Math.floor(code / 5); |
| 35 | + const targetCol = code % 5; |
| 36 | + |
| 37 | + while (row > targetRow) path += 'U', row--; |
| 38 | + while (col > targetCol) path += 'L', col--; |
| 39 | + while (row < targetRow) path += 'D', row++; |
| 40 | + while (col < targetCol) path += 'R', col++; |
| 41 | + |
| 42 | + path += '!'; |
| 43 | + } |
| 44 | + |
| 45 | + return path; |
| 46 | +}; |
0 commit comments