파비의 매일매일 공부기록

2023.09.17 Today's Challenge 본문

Problem Solving/LeetCode

2023.09.17 Today's Challenge

fabichoi 2023. 9. 17. 23:45

https://leetcode.com/problems/shortest-path-visiting-all-nodes/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

비트마스크와 BFS를 활용해 풀면 된다고 한다.

class Solution:
    def shortestPathLength(self, graph: List[List[int]]) -> int:
        n = len(graph)
        qu = deque([(1<<i, i, 0) for i in range(n)])
        visited = set((1<<i, i) for i in range(n))

        while qu:
            mask, node, dist = qu.popleft()
            if mask == (1<<n) - 1:
                return dist
            for nei in graph[node]:
                new_mask = mask | (1 << nei)
                if (new_mask, nei) not in visited:
                    visited.add((new_mask, nei))
                    qu.append((new_mask, nei, dist+1))
반응형

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

2023.09.19 Today's Challenge  (0) 2023.09.19
2023.09.18 Today's Challenge  (0) 2023.09.18
2023.09.16 Today's Challenge  (0) 2023.09.16
2023.09.15 Today's Challenge  (0) 2023.09.15
2023.09.14 Today's Challenge  (0) 2023.09.14
Comments