Print shortest path to print a string on screen
Given a 5x5 grid containing alphabets from A-Z and a string str. The task is to find the shortest path to type all characters of str in order. The starting position is at A (top-left corner).
Rules for Movement:
- You can move left, right, up, or down while staying inside the grid.
- For each character in str, move horizontally first (Left/Right), then vertically (Up/Down) to reach the target letter.
- Once you reach a character, print "OK" before moving to the next one.
Grid:
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
Z
Examples:
Input: str = "GFG"
Output: RIGHT DOWN OK LEFT OK RIGHT OK
Explanation:
- Start at A -> Move RIGHT to B, C, D, E, then DOWN to G -> OK
- Move LEFT to F->OK
- Move RIGHT to G -> OK
Input: str = "GEEK"
Output: RIGHT DOWN OK RIGHT RIGHT RIGHT UP OK OK LEFT LEFT LEFT LEFT DOWN DOWN OK
Explanation:
- Start at A -> Move RIGHT to B, C, D, E, then DOWN to G -> OK
- Move RIGHT to E -> OK
- Stay at E -> OK
- Move LEFT to D, C, B, A, then DOWN DOWN to K -> OK
Approach:
The idea is to treat the 5x5 grid as a coordinate plane and move step by step to reach each character. We first map each character's position in the grid, then start from 'A' (0,0) and navigate to each character in the input string using simple LEFT, RIGHT, UP, and DOWN moves. Since 'Z' is placed at (5,0), we handle it separately. At each step, we move in the necessary direction before confirming the selection with "OK."
Steps to implement the above idea:
- Map each character (A-Y, Z) to its 5x5 grid position.
- Start from 'A' (0,0) as the initial position.
- Iterate through the input string and find each character's target position.
- Move LEFT, RIGHT, UP, or DOWN step by step to reach the target.
- Append "OK" after reaching each character.
- Return the list of movements as the result.
Below is implementation of the above approach:
// C++ Code to print shortest possible path to
// type all characters of given string
#include <bits/stdc++.h>
using namespace std;
// Function to find the shortest path to type
// characters of str
vector<string> printPath(string str) {
vector<string> result;
// Store positions of characters in the 5x5 grid
unordered_map<char, pair<int, int>> pos;
char ch = 'A';
// Fill positions for characters A to Y
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5
&& ch <= 'Y'; j++, ch++) {
pos[ch] = {i, j};
}
}
// Position of 'Z' (last row, first column)
pos['Z'] = {5, 0};
// Start from 'A' at (0,0)
int x = 0, y = 0;
// Traverse each character in str
for (char c : str) {
// Extract target position manually
// (fix for C++14 compatibility)
int targetX = pos[c].first;
int targetY = pos[c].second;
// Move right if target is on the right
while (y < targetY) {
result.push_back("RIGHT");
y++;
}
// Move left if target is on the left
while (y > targetY) {
result.push_back("LEFT");
y--;
}
// Move down if target is below
while (x < targetX) {
result.push_back("DOWN");
x++;
}
// Move up if target is above
while (x > targetX) {
result.push_back("UP");
x--;
}
// Add "OK" when the target
// character is reached
result.push_back("OK");
}
return result;
}
void printArr(vector<string> &arr) {
for (const string &step : arr) {
cout << step << " ";
}
cout << endl;
}
int main() {
string str = "GFG";
vector<string> path = printPath(str);
printArr(path);
return 0;
}
// Java Code to print shortest possible path to
// type all characters of given string
import java.util.*;
class GfG {
// Function to find the shortest path to type
// characters of str
static ArrayList<String> printPath(String str) {
ArrayList<String> result = new ArrayList<>();
// Store positions of characters in the 5x5 grid
HashMap<Character, int[]> pos = new HashMap<>();
char ch = 'A';
// Fill positions for characters A to Y
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5
&& ch <= 'Y'; j++, ch++) {
pos.put(ch, new int[]{i, j});
}
}
// Position of 'Z' (last row, first column)
pos.put('Z', new int[]{5, 0});
// Start from 'A' at (0,0)
int x = 0, y = 0;
// Traverse each character in str
for (char c : str.toCharArray()) {
// Extract target position manually
// (fix for Java compatibility)
int targetX = pos.get(c)[0];
int targetY = pos.get(c)[1];
// Move right if target is on the right
while (y < targetY) {
result.add("RIGHT");
y++;
}
// Move left if target is on the left
while (y > targetY) {
result.add("LEFT");
y--;
}
// Move down if target is below
while (x < targetX) {
result.add("DOWN");
x++;
}
// Move up if target is above
while (x > targetX) {
result.add("UP");
x--;
}
// Add "OK" when the target
// character is reached
result.add("OK");
}
return result;
}
// Function to print list of strings
static void printArr(ArrayList<String> arr) {
for (String step : arr) {
System.out.print(step + " ");
}
System.out.println();
}
public static void main(String[] args) {
// Hardcoded input
String str = "GFG";
ArrayList<String> path = printPath(str);
printArr(path);
}
}
# Python Code to print shortest possible path to
# type all characters of given string
# Function to find the shortest path to type
# characters of str
def printPath(str):
result = []
# Store positions of characters in the 5x5 grid
pos = {}
ch = 'A'
# Fill positions for characters A to Y
for i in range(5):
for j in range(5):
if ch > 'Y':
break
pos[ch] = (i, j)
ch = chr(ord(ch) + 1)
# Position of 'Z' (last row, first column)
pos['Z'] = (5, 0)
# Start from 'A' at (0,0)
x, y = 0, 0
# Traverse each character in str
for c in str:
# Extract target position manually
# (fix for Python compatibility)
targetX, targetY = pos[c]
# Move right if target is on the right
while y < targetY:
result.append("RIGHT")
y += 1
# Move left if target is on the left
while y > targetY:
result.append("LEFT")
y -= 1
# Move down if target is below
while x < targetX:
result.append("DOWN")
x += 1
# Move up if target is above
while x > targetX:
result.append("UP")
x -= 1
# Add "OK" when the target
# character is reached
result.append("OK")
return result
# Function to print list of strings
def printArr(arr):
print(" ".join(arr))
if __name__ == "__main__":
# Hardcoded input
str = "GFG"
path = printPath(str)
printArr(path)
// C# Code to print shortest possible path to
// type all characters of given string
using System;
using System.Collections.Generic;
class GfG {
// Function to find the shortest path to type
// characters of str
public static List<string> printPath(string str) {
List<string> result = new List<string>();
// Store positions of characters in the 5x5 grid
Dictionary<char, int[]> pos = new Dictionary<char, int[]>();
char ch = 'A';
// Fill positions for characters A to Y
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5
&& ch <= 'Y'; j++, ch++) {
pos[ch] = new int[] {i, j};
}
}
// Position of 'Z' (last row, first column)
pos['Z'] = new int[] {5, 0};
// Start from 'A' at (0,0)
int x = 0, y = 0;
// Traverse each character in str
foreach (char c in str) {
// Extract target position manually
// (fix for C# compatibility)
int targetX = pos[c][0];
int targetY = pos[c][1];
// Move right if target is on the right
while (y < targetY) {
result.Add("RIGHT");
y++;
}
// Move left if target is on the left
while (y > targetY) {
result.Add("LEFT");
y--;
}
// Move down if target is below
while (x < targetX) {
result.Add("DOWN");
x++;
}
// Move up if target is above
while (x > targetX) {
result.Add("UP");
x--;
}
// Add "OK" when the target
// character is reached
result.Add("OK");
}
return result;
}
// Function to print list of strings
public static void printArr(List<string> arr) {
foreach (string step in arr) {
Console.Write(step + " ");
}
Console.WriteLine();
}
public static void Main(string[] args) {
// Hardcoded input
string str = "GFG";
List<string> path = printPath(str);
printArr(path);
}
}
// JavaScript Code to print shortest possible path to
// type all characters of given string
// Function to find the shortest path to type
// characters of str
function printPath(str) {
let result = [];
// Store positions of characters in the 5x5 grid
let pos = new Map();
let ch = 'A';
// Fill positions for characters A to Y
for (let i = 0; i < 5; i++) {
for (let j = 0; j < 5; j++) {
if (ch > 'Y') break;
pos.set(ch, [i, j]);
ch = String.fromCharCode(ch.charCodeAt(0) + 1);
}
}
// Position of 'Z' (last row, first column)
pos.set('Z', [5, 0]);
// Start from 'A' at (0,0)
let x = 0, y = 0;
// Traverse each character in str
for (let c of str) {
// Extract target position manually
// (fix for JavaScript compatibility)
let [targetX, targetY] = pos.get(c);
// Move right if target is on the right
while (y < targetY) {
result.push("RIGHT");
y++;
}
// Move left if target is on the left
while (y > targetY) {
result.push("LEFT");
y--;
}
// Move down if target is below
while (x < targetX) {
result.push("DOWN");
x++;
}
// Move up if target is above
while (x > targetX) {
result.push("UP");
x--;
}
// Add "OK" when the target
// character is reached
result.push("OK");
}
return result;
}
// Function to print list of strings
function printArr(arr) {
console.log(arr.join(" "));
}
// Hardcoded input
let str = "GFG";
let path = printPath(str);
printArr(path);
Output
RIGHT DOWN OK LEFT OK RIGHT OK
Time Complexity: O(n), as each character's position is found in O(1), and movement is processed in O(1) per character.
Space Complexity: O(n), as the result vector stores O(n) moves for an input string of length n.