# Adjacency List representation of a graph

I am looking to draw a graph knowing a simple adjacency representation of the graph like:

 A = {{1, 3}, {2, 3}, {3, 4, 5}, {4, 5}, {5}}


Where A is my Adjacency List. I was thinking I could use Graph[] and maybe some kind of pattern matching:

 Graph[{_\[DirectedEdge]_}]


I am also not familiar with patterns in mathematica (the "_" that gets used a lot but has been hard for me to understand).

• Are you missing one sub-list? You got 5 vertexes but 4 sub-lists. Mar 25, 2013 at 22:34
• @VitaliyKaurov you are 100% correct. I fixed it. Mar 25, 2013 at 22:48

Adjacency list "...is a collection of unordered lists, one for each vertex in the graph. Each list describes the set of neighbors of its vertex."

I will modify your list slightly to have a bit more interesting graph:

A = {{1, 3}, {2, 3}, {3, 4, 5}, {4, 5}, {1, 2, 4, 3}};


Then define a function:

el[x_] := Flatten[MapIndexed[Thread[First[#2] -> #1] &, x]]


And build your graph:

Graph[el[A], GraphStyle -> "SmallNetwork", GraphLayout -> "LayeredDigraphEmbedding"]


• My only issue is that my adjacency lists are defined such that the first element is the vertex and each subsequent element represents the edges. This definition would remove all of the 1-cycles in your implementation. Mar 25, 2013 at 23:04
• This is also a great example of neat mathematica programming but I don't understand what you are doing. Could you explain a little of what is going on? Mar 25, 2013 at 23:05
• if first element in your list is the starting vertex, then you could do Graph[Flatten[Thread[#1 [DirectedEdge] {##2}] & @@@ A]] Mar 26, 2013 at 1:56
• @MatthewKemnetz you would need to look up in the documentation how the functions work. Start with MapIndexed, then Thread, then Flatten. The main idea here is that you are building a Graph out of list of edges. To construct list of edges you need to connect index of the sub-list (vertex) with its elements (neighbor vertexes) by an edge ->. That what MapIndexed do. Mar 26, 2013 at 4:05

You can also construct the AdjacencyMatrix associated with A and use it with AdjacencyGraph:

am = SparseArray[Join @@ (Thread /@ MapIndexed[{First@#2, #} &, A]) ->  1];
AdjacencyGraph[am, GraphStyle -> "SmallNetwork", GraphLayout -> "LayeredDigraphEmbedding"]