Alphabet Board Path Problem in Java

We are provided with an alphabet board that consists all the letters of English language from A to Z as shown in the below mentioned diagram.

Alphabet Board Path Problem in Java

On the above-mentioned alphabet board, we start at the position (0,0) and we can take only the below-mentioned moves:

  • 'U' indicates that your position moves up by one row, only if it exists on the board.
  • 'D' indicates that your position moves down by one row, only if it exists on the board.
  • 'L' indicates that your position moves left by one column, only if it exists on the board.
  • 'R' indicates that your position moves right by one column, only if it exists on the board.
  • '!' indicates that the character board[row][column] will be added at the current positon (row, column) of the answer.

Solution to the Problem

Obtain all letters' positions. For each pair of adjacent letters, obtain the path by the difference between the two positions' rows and the difference between the two positions' columns. When each letter is to be typed, add the path from the previous position to the current position to the sequence, and add '!' to the sequence.

If the current letter or the previous letter is z, then the path needs to be obtained differently. Since z is only letter in the last row, it is impossible to move left in the last row to reach z, and it is also impossible to move right in the last row from z. Therefore, to move to z, first move left to the leftmost column then move down. To move from z, first move up then move right (if the next letter is not in the leftmost column).

Finally, return the sequence.

Example 1:

Input: "English"

Output: DDDDD!UUURRR!ULL!D!URR!DD!UUL!

Example 2:

Input: "Alphabets"

Output: DDDDD!UUUR!DL!UURR!ULL!R!RRR!DDD!L!

Filename: AlphabetBoardPath.java

Output:

DDDDD!UUUR!DL!UURR!ULL!R!RRR!DDD!L!





Latest Courses