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 →

  • 243avinash
    3 months ago+ 0 comments

    The easiest code in python to understand and implement for u:

    def bfs(n, m, edges, s):
        graph = {}
        for i in range(1,n+1):
            graph[i] = []
       
        for v1,v2 in edges:
            graph[v1].append(v2)
            graph[v2].append(v1)
        
        visited = [s]
        queue = [s]
        level = [None]*(n)
        level[s-1] = 0
        while queue:
            devertex = queue.pop(0)
            for neighbours in graph[devertex]:
                if neighbours not in visited:
                    level[neighbours-1] = level[devertex-1]+6
                    visited.append(neighbours)
                    queue.append(neighbours)
        res = []
        for i in level:
            if i == None:
                res.append(-1)
            else:
                if i != 0:
                    res.append(i)
        return res
    
    0|
    Permalink
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy