파비의 매일매일 공부기록

2023.11.12 Today's Challenge 본문

Problem Solving/LeetCode

2023.11.12 Today's Challenge

fabichoi 2023. 11. 12. 23:45

https://leetcode.com/problems/bus-routes/

 

Bus Routes - LeetCode

Can you solve this real interview question? Bus Routes - You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever. * For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in

leetcode.com

이번에도 BFS로 푸는 문제

class Solution:
    def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
        if source == target:
            return 0
        
        max_stop = max(max(route) for route in routes)
        if max_stop < target:
            return -1

        n = len(routes)
        min_buses_to_reach = [float('inf')] * (max_stop + 1)
        min_buses_to_reach[source] = 0

        flag = True
        while flag:
            flag = False
            for route in routes:
                m = float('inf')
                for stop in route:
                    m = min(m, min_buses_to_reach[stop])
                m += 1
                for stop in route:
                    if min_buses_to_reach[stop] > m:
                        min_buses_to_reach[stop] = m
                        flag = True
        
        return min_buses_to_reach[target] if min_buses_to_reach[target] < float('inf') else -1
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.11.14 Today's Challenge  (0) 2023.11.14
2023.11.13 Today's Challenge  (0) 2023.11.13
2023.11.11 Today's Challenge  (1) 2023.11.11
2023.11.10 Today's Challenge  (0) 2023.11.10
2023.11.09 Today's Challenge  (0) 2023.11.09
Comments