Graph Theory should be illustrated.
I'm starting to learn scala-graph by example. In each post, I will post the sample code and the generated pictures.
The following code shows how to creat a graph, calculate the shortest path of two nodes and export the particular graph with a highlighted path to dot format.
import scalax.collection.Graph
import scalax.collection.GraphEdge.DiEdge
import scalax.collection.GraphPredef._
import scalax.collection.io.dot._
import implicits._
import java.io.PrintWriter
import sys.process._
object Main extends App {
val dg = Graph(0~>1, 2~>0, 2~>3, 3~>2, 3~>5, 4~>2,
4~>3, 5~>4, 6~>0, 6~>4, 6~>9, 7~>6, 7~>8, 8~>7,
8~>9, 9~>10, 9~>11, 10~>12, 11~>12, 12~>9)
def n(outer: Int): dg.NodeT = dg get outer
val path = (n(7) shortestPathTo n(0)).get
val root = new DotRootGraph(true, id = Some(Id("Dot")))
def edgeTransformer(graph: Graph[Int, DiEdge], path: Graph[Int, DiEdge]#Path,
innerEdge: Graph[Int,DiEdge]#EdgeT): Option[(DotGraph,DotEdgeStmt)]
= innerEdge match {
case graph.EdgeT(source, target) =>
if (path.edges.exists(e => e.equals(innerEdge)))
Some((root, DotEdgeStmt(source.toString, target.toString,
List(DotAttr("color", "#ff0000")))))
else
Some((root, DotEdgeStmt(source.toString, target.toString)))
}
val dot = dg.toDot(root, edgeTransformer(dg, path, _))
val dotFile = new PrintWriter("graph.dot")
dotFile.println(dot.toString)
dotFile.close
"dot -Tpng graph.dot -o graph.png" !
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。