J'ai essayé d'utiliser la bibliothèque GraphStream pour trouver le chemin le plus court entre 2 nœuds dans un graphique. À la fin, je suis en mesure d'imprimer les bords du chemin (it.foreach(println)
) mais je ne peux pas accéder à un élément à la fois. Voici le code:Comment utiliser la bibliothèque GraphStream pour Scala
import org.graphstream.algorithm.Dijkstra;
import org.graphstream.graph.Edge;
import org.graphstream.graph.Graph;
import org.graphstream.graph.Node;
import org.graphstream.graph.Path;
import org.graphstream.graph.implementations.SingleGraph;
import scala.collection.JavaConverters._
object MainApp extends App{
def exampleGraph():Graph={
val g:Graph = new SingleGraph("example");
g.addNode("N1_S1");
g.addNode("N1_J1");
g.addNode("N1_H1");
g.addNode("N1_J2");
g.addNode("N1_H2");
g.addNode("N1_W1");
var e:Edge=g.addEdge("N1_S1-N1_J1", "N1_S1", "N1_J1")
e.addAttribute("length",Int.box(6))
e=g.addEdge("N1_J1-N1_H1", "N1_J1", "N1_H1")
e.addAttribute("length",Int.box(8))
e=g.addEdge("N1_J1-N1_J2", "N1_J1", "N1_J2")
e.addAttribute("length",Int.box(8))
e=g.addEdge("N1_J2-N1_H2", "N1_J2", "N1_H2")
e.addAttribute("length",Int.box(4))
e=g.addEdge("N1_J2-N1_W1", "N1_J2", "N1_W1")
e.addAttribute("length",Int.box(10))
return g
}
val g:Graph = exampleGraph();
g.display(false);
val dijkstra:Dijkstra = new Dijkstra(Dijkstra.Element.EDGE, null, "length");
dijkstra.init(g);
dijkstra.setSource(g.getNode("N1_S1"));
println(dijkstra.getPath(g.getNode("N1_W1")));
val myPath:Path=dijkstra.getPath(g.getNode("N1_W1"))
val it=(myPath.getEachEdge).asScala
println("edges")
it.foreach(println)
}
Le problème est que le prototype de getEachEdge
est getEachEdge[T <: Edge](): Iterable[_ <: T]
et asScala
renvoie un Iterable[_ <: Nothing]
. Donc, la dernière question est "Comment puis-je accéder à chaque élément du chemin le plus court?"
Quelle version scala utilisez-vous? –