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" !
}

References

  1. 啄木鸟社区的GraphViz页面

  2. scala类型系统:4) 内部类,路径依赖类型&类型投影


溢出的达达
521 声望8 粉丝

《Scala实用指南》译者,GNU TeXmacs维护者。