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 character board[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.
For example:
Input: target = "leet" Output: "DDR!UURRR!!DDD!"
Input: target = "code" Output: "RR!DDRR!UUL!R!"
Constraints:
1 <= target.length <= 100 target consists only of English lowercase letters.
A brute-force approach would involve exploring all possible paths on the board to construct the target string. This can be done using a graph traversal algorithm such as Depth-First Search (DFS) or Breadth-First Search (BFS).
However, this approach is highly inefficient due to the exponential number of possible paths. It will likely result in a Time Limit Exceeded (TLE) error for larger target strings.
Time Complexity: O(4N), where N is the length of the target string (very high complexity).
Space Complexity: O(N), due to recursion depth or queue size in DFS/BFS.
A more efficient solution involves directly calculating the movements required to reach each character in the target string from the current position. We can iterate through the target string and, for each character, determine the sequence of 'U', 'D', 'L', 'R' moves to reach that character from the previous character, appending a '!' to select the character.
Here's a step-by-step breakdown:
def alphabetBoardPath(target: str) -> str:
board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"]
pos = {}
for r in range(len(board)):
for c in range(len(board[r])):
pos[board[r][c]] = (r, c)
curr_r, curr_c = 0, 0
res = ""
for char in target:
target_r, target_c = pos[char]
dr = target_r - curr_r
dc = target_c - curr_c
if dr > 0:
res += "D" * dr
if dc > 0:
res += "R" * dc
if dr < 0:
res += "U" * abs(dr)
if dc < 0:
res += "L" * abs(dc)
res += "!"
curr_r, curr_c = target_r, target_c
return res
Time Complexity: O(N), where N is the length of the target string, as we iterate through it once.
Space Complexity: O(1), as we use a constant amount of extra space (ignoring the output string).