当前位置:网站首页>The problem of finding three color flags in C language test 165

The problem of finding three color flags in C language test 165

2022-06-09 22:18:00 Maserati

Personal home page : Personal home page
Series column :C Language test questions 200 example
Recommend a brush algorithm 、 written examination 、 Face the 、 Nada Corporation offer Artifact Click jump to enter the website
Author's brief introduction : Hello everyone , I'm Maserati ,CSDN Blogger ( Ranking of the whole station Top 50), Alibaba cloud blog expert 、51CTO Blogger 、 Huawei cloud sharing expert

1、 subject

subject : There's a rope , There's red on it 、 white 、 Flags in three colors of blue . The colors of the flags on the rope are out of order , Now we have to classify the flags , According to blue 、 white 、 In red order . You can only move on the rope , And only two flags can be exchanged at a time , How to move the flag so that it can be moved at least ?:

analysis :
The flag moves on the rope , And only two flags can be exchanged at a time , So just make sure that when you move the flag , Start at the beginning of the rope , The blue flag moves forward , The white flag is left in the middle , The red flag moves backwards . To minimize the number of moves , You can use three pointers b、w、r As blue flag 、 White and red flags .

if w The current flag pointed by the pointer is white , be w The pointer increases 1, It means adding one side to the white flag . if w The current flag pointed by the pointer is blue , Will b The pointer and w The flags pointed to by the pointer are exchanged , meanwhile b The pointer and w The pointer increases 1, It means that both the blue flag and the white flag have an element . if w The pointer points to

原网站

版权声明
本文为[Maserati]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206092135276231.html