Print shortest path to print a string on screen in C Program.

Given a string, the program must display the shortest path which will print the string over the screen using that shortest path. The alphabets are arranged on a virtual keyboard in a 5x5 grid format.

The keyboard layout is −

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

Syntax

void printpath(char str[]);

Algorithm

The approach stores characters in a matrix and calculates the shortest path by −

  • If row difference is negative then move up
  • If row difference is positive then move down
  • If column difference is negative then move left
  • If column difference is positive then move right

Example

For input string "HUP", the output shows the movement sequence −

#include <stdio.h>

void printpath(char str[]){
    int i = 0;
    // start from character 'A' present at position (0, 0)
    int cx = 0, cy = 0;
    
    while (str[i] != '\0'){
        // find coordinates of next character
        int n1 = (str[i] - 'A') / 5;
        int n2 = (str[i] - 'A') % 5;
        
        // Move Up if destination is above
        while (cx > n1){
            printf("Move Up<br>");
            cx--;
        }
        
        // Move Left if destination is to the left
        while (cy > n2){
            printf("Move Left<br>");
            cy--;
        }
        
        // Move down if destination is below
        while (cx < n1){
            printf("Move Down<br>");
            cx++;
        }
        
        // Move Right if destination is to the right
        while (cy < n2){
            printf("Move Right<br>");
            cy++;
        }
        
        // At this point, destination is reached
        printf("destination reached<br>");
        i++;
    }
}

int main(){
    char str[] = "HUP";
    printpath(str);
    return 0;
}
Move Down
Move Down
destination reached
Move Down
Move Down
Move Down
destination reached
Move Up
destination reached

How It Works

The program calculates coordinates for each character −

  • Row position: (character - 'A') / 5
  • Column position: (character - 'A') % 5
  • Starting from position (0,0) for 'A', it moves to each target character's position
  • For 'H': row 1, col 2 − moves down once, right twice
  • For 'U': row 4, col 0 − moves down three times, left twice
  • For 'P': row 3, col 0 − moves up once

Conclusion

This algorithm efficiently finds the shortest Manhattan distance path on a grid keyboard layout. It processes each character sequentially and outputs the minimum moves required to reach each destination.

Updated on: 2026-03-15T12:00:05+05:30

372 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements