Skip to content

Instantly share code, notes, and snippets.

@tyuki39
Created April 11, 2011 14:47
Show Gist options
  • Save tyuki39/913629 to your computer and use it in GitHub Desktop.
Save tyuki39/913629 to your computer and use it in GitHub Desktop.
一方通行迷路の結果をGraphVizのdotにするためのコード
// XMLの形状は下記の通り(10x10の迷路限定)
// ( from http://d.hatena.ne.jp/aya_eiya/20110329/1301406161 )
// <labyrinth>
// <cell doors='East:true,West:false,South:true,North:false' position='1,1'></cell>
// <cell doors='East:true,West:false,South:true,North:false' position='1,2'></cell>
// ...
// <cell doors='East:false,West:true,South:false,North:true' position='10,10'></cell>
// </labyrinth>
//
// 実行後の出力結果を次のように GraphViz に与える
// dot -Tpng output.txt -o labyrinth.png
def labyrinth = new XmlParser().parse(new File('labyrinth.xml'))
def edges = [:]
labyrinth.each {
def pos = it.'@position'.split(',')
def col = pos[0] as int
def row = pos[1] as int
if( edges[[col,row]] == null ) edges[[col,row]] = new ArrayList()
def doors = it.'@doors'.split(',')
def east = doors[0].split(':')[1].toBoolean()
def west = doors[1].split(':')[1].toBoolean()
def south = doors[2].split(':')[1].toBoolean()
def north = doors[3].split(':')[1].toBoolean()
edges[[col,row]] = [ east, west, south, north ]
}
// グラフヘッダ
println """
digraph labyrinth {
rankdir=LR;
node [ shape = box ];"""
(1..10).each { col ->
// クラスタヘッダ
println """
subgraph cluster${col} {
labeljust=l;"""
// クラスタ内の全ノードを出力
(1..10).each { row ->
println " R${col}${row} [ label = \"R(${col},${row})\" ];"
}
// 同じ行のノードを揃えるための不可視エッジを出力
(1..<10).each { row ->
println " R${col}${row} -> R${col}${row+1} [style=invis]"
}
// ドアの開閉状態に対応する水平方向のエッジを出力
(1..10).each { row ->
if( edges[[col,row]][0] ) println " R${col}${row} -> R${col}${row+1} [ color=blue ];"
if( edges[[col,row]][1] ) println " R${col}${row} -> R${col}${row-1} [ color=red ];"
}
// クラスタフッタ
println """
}"""
}
// 同じ列のノードを揃えるための不可視エッジを出力
(1..<10).each { col ->
println " R${col}1 -> R${col+1}2 [style=invis, weight=10]"
println " R${col+1}1 -> R${col}2 [style=invis, weight=10]"
println " R${col}9 -> R${col+1}10 [style=invis, weight=10]"
println " R${col+1}9 -> R${col}10 [style=invis, weight=10]"
(1..10).each { row ->
println " R${col}${row} -> R${col+1}${row} [style=invis]"
}
}
// ドアの開閉状態に対応する垂直向のエッジを出力
(1..10).each { col ->
(1..10).each { row ->
if( edges[[col,row]][2] ) { println " R${col}${row} -> R${col+1}${row} [ color=blue ];" }
if( edges[[col,row]][3] ) { println " R${col}${row} -> R${col-1}${row} [ color=red ];" }
}
}
// グラフフッタ
println """
}"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment