首頁 > 後端開發 > C++ > 主體

列印最短路徑以在 C 程式中在螢幕上列印字串。

WBOY
發布: 2023-09-07 23:21:04
轉載
1142 人瀏覽過

打印最短路径以在 C 程序中在屏幕上打印字符串。

Given a string, the program must display the shortest path which will print the string over the screen using that shortest path.

Like screen will store alphabets in the format

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
登入後複製

Example

的中文翻译为:

示例

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
登入後複製

Example

的中文翻译为:

示例

#include <stdio.h>
void printpath(char str[]){
   int i = 0;
   // start from character &#39;A&#39; present at position (0, 0)
   int cx = 0, cy = 0;
   while (str[i] != &#39;\0&#39;){
      // find cordinates of next character
      int n1 = (str[i] - &#39;A&#39;) / 5;
      int n2 = (str[i] - &#39;B&#39; + 1) % 5;
      // Move Up if destination is above
      while (cx > n1){
         printf("Move Up</p><p>");
         cx--;
      }
      // Move Left if destination is to the left
      while (cy > n2){
         printf("Move Left</p><p>");
         cy--;
      }
      // Move down if destination is below
      while (cx < n1){
         printf("Move Down</p><p>");
            cx++;
      }
      // Move Right if destination is to the right
      while (cy < n2){
         printf("Move Down</p><p>");
         cy++;
      }
      // At this point, destination is reached
      printf("destination reached</p><p>");
      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
登入後複製

以上是列印最短路徑以在 C 程式中在螢幕上列印字串。的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!