阿D的最佳飞行路线探索

101 阅读2分钟

问题描述:

小C和他的领导小F计划一次飞行,但由于严格的航空管制,他们的飞机仅能按特定的路线飞行:飞机只能飞往当前机场的相邻机场或相同航空公司管理的机场。为了减少起飞次数,小C需要制定最优的飞行路线。机场由一个数组airports标识,其中:

数组每个元素代表一个独特的机场,元素的值代表不同的航空公司。

airports[0]为起点,airports[airports.length - 1]为终点。

假设小C当前在机场i,那么i - 1和i + 1(如果存在)代表邻近机场,飞机可以直接前往。

如果在机场i,且存在airports[i] == airports[j],则机场i和机场j同属一家航空公司,可直接飞往。

求最小起飞次数

测试样例:

样例一:

输入:airports = [10, 12, 13, 12, 14] 输出:3

样例二:

输入:airports = [10, 11, 12, 13, 14] 输出:4

样例三:

输入:airports = [7, 7, 7, 8, 9, 7] 输出:1

题目难度:中等

解题语言:python

思路:

我们可以使用广度优先搜索(BFS)来找到从起点到终点的最短路径。BFS 非常适合这种问题,因为它会逐层扩展,确保我们找到的是最短路径。然后使用队列(deque)来进行 BFS。再使用集合(set)来记录已经访问过的机场,避免重复访问。

步骤:

1.初始化队列,将起点(airports[0])和起飞次数(0)加入队列。

2.从队列中取出当前机场和当前起飞次数。如果当前机场是终点,返回当前起飞次数。

3.否则,将当前机场的相邻机场和同一家航空公司的机场加入队列,并标记为已访问。

4.继续上述步骤,直到队列为空。

代码:

from collections import deque

def solution(airports): # 初始化队列和已访问集合 queue = deque([(0, 0)]) # (当前机场索引, 起飞次数) visited = set([0]) # 已访问的机场索引

while queue:
    current_index, takeoff_count = queue.popleft()
    
  
    if current_index == len(airports) - 1:
        return takeoff_count
    
   
    current_airline = airports[current_index]
    
  
    for neighbor_index in [current_index - 1, current_index + 1]:
        if 0 <= neighbor_index < len(airports) and neighbor_index not in visited:
           
            queue.append((neighbor_index, takeoff_count + 1))
            visited.add(neighbor_index)
    
  
    for i in range(len(airports)):
        if airports[i] == current_airline and i not in visited:
          
            queue.append((i, takeoff_count + 1))
            visited.add(i)


return -1
if __name__ == "__main__":

print(solution([10, 12, 13, 12, 14]) == 3)
print(solution([10, 11, 12, 13, 14]) == 4)