【问题标题】:2D map to graph in Sml2D 映射到 Sml 中的图形
【发布时间】:2017-05-03 06:08:02
【问题描述】:

我有一个 2D 地图作为文件的逐行输入,我想保存它并运行 Bfs 或 Dijkstra 以找到从 Start(标记为 S)到 end(标记为 E)的最短路径,什么是保存信息的正确结构?我在 c++ 中的实现是使用图表,但我发现在 sml 中很难这样做,因为我无法双向链接节点。

【问题讨论】:

标签: graph sml smlnj


【解决方案1】:

您可以使用可变数组来做到这一点。这是一个使用int option 数组的极小邻接矩阵实现。顶点ij 之间的边由ith 行和jth 列中的值给出。如果值为None,则没有边,如果值为Some w,则边存在且权重为w

let is_some opt =
  match opt with
  | None -> false
  | _ -> true;;

let unwrap opt =
  match opt with
  | None -> raise (Failure "unwrapped None")
  | Some x -> x;;

let add_edge g u v w =
  let us = Array.get g u in
  Array.set us v (Some w);;

let get_edge g u v =
  let us = Array.get g u in
  Array.get us v;;

let make_graph vertices =
  Array.make_matrix vertices vertices None;;

let neighbors g u =
  Array.get g u |>
  Array.to_list |>
  List.filter is_some |>
  List.mapi (fun i o -> (i, unwrap o));;


let g = make_graph 4;;
add_edge g 0 1 2;;
add_edge g 0 2 3;;
add_edge g 0 3 5;;
add_edge g 1 2 7;;
add_edge g 1 3 11;;
add_edge g 2 3 13;;
add_edge g 3 0 17;;
List.iter (fun (v, e) -> Printf.printf "0-(%i)->%i\n" e v) (neighbors g 0);;

这是在 OCaml 中,但 SML 和 OCaml 之间的差异在很大程度上是很小的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 2018-10-03
    • 2013-01-08
    • 1970-01-01
    • 2013-12-17
    相关资源
    最近更新 更多