We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Hackerrank Home
  • Prepare
    NEW
  • Certify
  • Compete
  • Career Fair
  • Hiring developers?
  1. Prepare
  2. Algorithms
  3. Graph Theory
  4. Breadth First Search: Shortest Reach
  5. Discussions

Breadth First Search: Shortest Reach

Problem
Submissions
Leaderboard
Discussions
Editorial

    You are viewing a single comment's thread. Return to all comments →

  • MOPKOBKA
    3 months ago+ 0 comments

    Python:

    from collections import deque, defaultdict
    
    def bfs(n, m, edges, s, cost = 6):
        
        graph = defaultdict(list)
        for u, v in edges:
            graph[u] += [v]
            graph[v] += [u]
        
        res = [-1] * (n+1)
        res[s] = 0
        q = deque([(s, 0)])
        
        while q:
            node, total = q.popleft()
            total += cost
            for i in graph[node]:
                if res[i] == -1:
                    q.append((i, total))
                    res[i] = total
        
        return res[1:s] + res[s+1:]
    
    0|
    Permalink
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy