Given a device having left, right, top, and bottom buttons and an OK button to enter a text from a virtual keypad having alphabets from A–Y arranged in a 5 × 5 grid, as shown below. Find the shortest route in the device to construct a given string if we start from the top-left position in the keypad.

For example,

Keypad:
 
A  B  C  D  E
F  G  H  I  J
K  L  M  N  O
P  Q  R  S  T
U  V  W  X  Y
 
Device:
 
    T
 L  M  R
    B
 
where,
 
T — Move up
B — Move down
L — Move left
R — Move right
M — Press OK

The shortest route to construct string TECHIE with the device’s help is BBBRRRRMTTTMLLMBMRMTRM.

 
The idea is to consider all characters of the specified string, and for each character, print out the shortest route to the next character from it. For finding the shortest route, compare the coordinates of the current character with the coordinates of the next character in the matrix. Based on the difference between the x–coordinate and y–coordinate of the current and next character, move left, right, top, or bottom.

Following is the implementation in C++, Java, and Python based on the above idea:

C++


Download  Run Code

Output:

BBBRRRRMTTTMLLMBMRMTRM

Java


Download  Run Code

Output:

BBBRRRRMTTTMLLMBMRMTRM

Python


Download  Run Code

Output:

BBBRRRRMTTTMLLMBMRMTRM

The time complexity of the above solution is O(n.c), where n is the input string’s length and c is a constant less than equal to 10. The auxiliary space required by the program is O(1).

 
Author: Aditya Goel