문자열이 주어지면 프로그램은 해당 최단 경로를 사용하여 화면에 문자열을 인쇄할 최단 경로를 표시해야 합니다.
Like screen은 알파벳을 형식으로 저장합니다.
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
예시
Input: HUP Output : Move Down Move Down Move Down destination reached Move Left Move Left Move Down Move Down Move Down destination reached Move Up destination reached
여기에 사용된 접근 방식은 n x n 행렬에 문자를 저장하고 다음 작업을 수행하는 것입니다 -
If row difference is negative then move up If row difference is positive then move down If column difference is negative then go left If column difference is positive then we go right
알고리즘
START
Step 1 -> Declare Function void printpath(char str[])
Declare variable int i = 0 and cx=0 and cy=0
Loop While str[i] != '\0'
Declare variable as int n1 = (str[i] - 'A') / 5
Declare variable as int n2 = (str[i] - 'B' + 1) % 5
Loop while cx > n1
Print move up
cx—
End
Loop while cy > n2
Print Move Left
Cy—
End
Loop while cx < n1
Print move down
Cx++
End
Loop while cy < n2
Print move down
Cy++
End
Print destination reached
I++
Step 2 -> in main()
Declare char str[] = {"HUP"}
Call printpath(str)
STOP 예시
#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 cordinates of next character
int n1 = (str[i] - 'A') / 5;
int n2 = (str[i] - 'B' + 1) % 5;
// Move Up if destination is above
while (cx > n1){
printf("Move Up\n");
cx--;
}
// Move Left if destination is to the left
while (cy > n2){
printf("Move Left\n");
cy--;
}
// Move down if destination is below
while (cx < n1){
printf("Move Down\n");
cx++;
}
// Move Right if destination is to the right
while (cy < n2){
printf("Move Down\n");
cy++;
}
// At this point, destination is reached
printf("destination reached\n");
i++;
}
}
int main(int argc, char const *argv[]){
char str[] = {"HUP"};
printpath(str);
return 0;
} 출력
위의 프로그램을 실행하면 다음과 같은 출력이 생성됩니다 -
Move Down Move Down Move Down destination reached Move Left Move Left Move Down Move Down Move Down destination reached Move Up destination reached