Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Min distance between 2 nodes in graph

def min_distance(a, b, graph)
    visited = {}
    distance = {}
    queue = Queue.new
    queue.enqueue(a)
    visited[a] = true
    distance[a] = 0
    
    while !queue.is_empty?
        current_node = queue.dequeue
        
        current_node.adjacent_nodes.each do |adjacent_node|
            if !visited[adjacent_node]
                distance[adjacent_node] = distance[current_node] + 1
                queue.enqueue(adjacent_node)
                visited[adjacent_node] = true
            end
        end
    end
    distance[b]
end

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.