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:


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

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

2 Answers 2


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"]

enter image description here

  • $\begingroup$ 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. $\endgroup$ Mar 25, 2013 at 23:04
  • $\begingroup$ 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? $\endgroup$ Mar 25, 2013 at 23:05
  • $\begingroup$ if first element in your list is the starting vertex, then you could do Graph[Flatten[Thread[#1 [DirectedEdge] {##2}] & @@@ A]] $\endgroup$
    – halmir
    Mar 26, 2013 at 1:56
  • $\begingroup$ @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. $\endgroup$ 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"]

Mathematica graphics


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.