Alphabet Board Path Problem
Description
LeetCode Problem 1138.
On an alphabet board, we start at position (0, 0), corresponding to character board[0][0].
Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"], as shown in the diagram below.

We may make the following moves:
'U'moves our position up one row, if the position exists on the board;'D'moves our position down one row, if the position exists on the board;'L'moves our position left one column, if the position exists on the board;'R'moves our position right one column, if the position exists on the board;'!'adds the characterboard[r][c]at our current position(r, c)to the answer.
(Here, the only positions that exist on the board are positions with letters on them.)
Return a sequence of moves that makes our answer equal to target in the minimum number of moves. You may return any path that does so.
Example 1:
Input: target = "leet"
Output: "DDR!UURRR!!DDD!"
Example 2:
Input: target = "code"
Output: "RR!DDRR!UUL!R!"
Constraints:
1 <= target.length <= 100targetconsists only of English lowercase letters.
Solution
Approach: Walk Letter by Letter
Letter ch sits at row v / 5 and column v % 5, where v = ch - 'a'. Between two letters, the shortest walk is the Manhattan distance: move vertically by the row difference and horizontally by the column difference, then press !. Doing this for each letter of target in turn gives a shortest path overall, since every letter has to be visited in this order anyway.
The only catch is 'z', alone in the last row at column 0. The cells to its right do not exist, so the order of the moves matters:
- Going to
'z'from, say,'y', moving down first would step from(4, 4)to the missing cell(5, 4). We must move left first, then down. - Going from
'z'to, say,'e', moving right first would leave the board. We must move up first, then right.
Always moving left, then up, then right, then down handles both: left and up only lead towards row 0 and column 0, where every cell exists, and by the time we move down into the last row we are already in column 0.
Complexity: O(n) time for a target of length n (each step is at most 9 moves), and O(n) space for the answer.
class Solution:
def alphabetBoardPath(self, target: str) -> str:
r = c = 0
moves = []
for ch in target:
v = ord(ch) - ord("a")
tr, tc = v // 5, v % 5
# Left and up first, right and down last: this way we never step off the board around 'z'.
moves.append("L" * max(0, c - tc))
moves.append("U" * max(0, r - tr))
moves.append("R" * max(0, tc - c))
moves.append("D" * max(0, tr - r))
moves.append("!")
r, c = tr, tc
return "".join(moves)