


How to use breadth-first search in Python to traverse the chaotic subway
Apr 28, 2023 am 08:01 AMChaotic subway problem
[Problem description]
The subway network in a certain city is extremely chaotic. There are n subway stations on a subway line, numbered 1 to n. There are subway stops at every station on the subway line. There is a number m on each subway station, which represents the number of stops that passengers must take from this station. Every metro station has metro lines going in both directions. Therefore, you can advance m stations in the direction with a larger number, or you can advance m stations in the direction with a smaller number. However, if you go beyond the scope of a subway station, you cannot ride the subway. For example, the number on the subway numbered 1 is 3. If you get on the train at that subway station, you can sit in the forward direction to the No. 4 subway station. But you cannot take the bus in the opposite direction to the -2 subway station, because the -2 subway station does not exist. Now a passenger starts from subway station A and wants to reach subway station B. Can he reach it? How many subway rides do he need at least?
[Input form]
Enter the number of subway stations in the first line
The second line in sequence Enter the number of each subway station, separated by spaces
In the third line, enter subway stations A and B, separated by spaces
[Output format]
Minimum number of subway rides from subway station A to B
[Sample input]
5
2 4 1 2 3
1 2
【Sample output】
2
Programming
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
Summary
Breadth-first search traversal is mainly implemented through a queue. The specific format is:
1 2 3 4 5 6 7 8 9 |
|
First put the first element into the queue, and then put the first element Take it out and find all the legal elements and put them into the queue, and then take them out from the queue one by one until the queue is empty, which means that all legal elements have been traversed.
The above is the detailed content of How to use breadth-first search in Python to traverse the chaotic subway. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What are the advantages and disadvantages of templating?

Google AI announces Gemini 1.5 Pro and Gemma 2 for developers

For only $250, Hugging Face's technical director teaches you how to fine-tune Llama 3 step by step

Share several .NET open source AI and LLM related project frameworks

A complete guide to golang function debugging and analysis
