What is a good data structure to represent an undirected graph?

旧时模样 提交于 2019-12-03 15:49:15
Darknight

OK I'm not familiar with this language (please pardon my ignorance):

I'd simply use the following structure:

V.E1.E2.En+1
V2.E1.E2.En+1
Vn+1.E1.E2.En+1

so basically the first digit before the decimal would represent the Vertice, and each Edge would be represented followed by a decimal point (kind of like an IP address)

such that:

could be stored as:

1.2.5

2.1.5.3

3.2.4

4.3.5.6

5.1.2.4

6.4

Then in your code, its simple to add/delete edges, and very easy to parse (because the vertice is always the first number)

ShuggyCoUk

There are several possibilities with differing pros and cons suited to different operations on the graphs. This nice intro gives background and examples of using Adjacency Lists and Adjacency Matrices.

Using them in an undirected fashion involves trade offs (space verses speed). this course material goes into more detail on the adjacency list style and provides some thoughts on the possible alterations for use in undirected usage.

A really easy one would be a hashtable, with the key as the source node, and the value as a list of connecting nodes. Then write an add function that does two hashtable insertions, one as (src, tgt), the other as (tgt, src).

In ocaml:

let add n1 n2 =
  let aux n1 n2 =
    match Hashtbl.find_option tbl n1 with
    | None -> Hashtbl.add tbl n1 [n2]
    | Some nodes -> Hashtbl.replace tbl n1 (n2::nodes)
  in
  let _ = aux n1 n2 in
  aux n2 n1

This would be a directed graph, it's just you would add both directions on insert. The hashtable lookup function will act as your connected function.

(Actually, in Ocaml hashtables offer multiple values for a key, so you could just use the Hashtbl.find_all function and save the list. But this is the easiest to translate into SML.)

We can represent a graph as a list of lists,we call this datastructure: an adjacency list .

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!