How to save a map and create a graph with BFS in Ruby

So, I think this is a classic question for someone with an MSC in CS.

I have an element N and I have distances. Say I have 3 elements with the following distances. It is symmetric, therefore

A -> B == B -> A

It looks like a matrix:

   A,  B,  C,  
A  0, 10,  20 
B 10,  0,  30
C 20, 30,   0

My question is:

  • how can i store this efficiently (what data structure)
  • What is the most efficient way to get a linked list where the minimum amount is minimal.

In this case, the best

B -> A -> C = 30 which equals to C -> A -> B

another case:

A -> B -> C = 40 which equals to C -> B -> A

I got the impression that BFS might be suitable for this. The link to the documentation in English is good, even the books on Amazon ...

+3
source share
2

- .

- ( ). , , .

:

vertices = {}
a = Vertex.new
b = Vertex.new

a.add(b, 10)
b.add(a, 10)

vertices[a] = a
vertices[b] = b

Dijkstra.

, . () node . node, node, .

, :

def traceback(parent, start, node, path)
  if(start == node)
     (path + start.to_s).reverse
  else
     path += node.to_s + " "
     traceback(parent, start, parent[node], path)
  end
end
+4
-1

Source: https://habr.com/ru/post/1781759/


All Articles