Creating and Using Adjacency Lists

Words: 562

An adjacency list is a data structure commonly used in graph theory.

How to build an adjacency list — template, and when to pick a list over a matrix

An adjacency list does roughly what an adjacency matrix does: it stores every edge of a graph. The difference is that a matrix wastes memory — with small data an adjacency matrix is still workable,

but once the data grows, a matrix usually runs out of time or memory, and that is when you switch to an adjacency list. To make the two representations easier to compare, let’s fix a small data set:

1 10 3 5 8 9

We mark the given points with 1 and leave the rest 0. (1) Adjacency matrix (fine for small, dense graphs)

/
0000000001
0000000000
0000100000
0000000000
0000000000
0000000000
0000000000
0000000010
0000000000
0000000000

As you can see, three points force us to allocate a 10x10 two-dimensional array — a large waste of space.

Walking such a graph with big data can also run out of time. So what about an adjacency list?

(2) Adjacency list (fine for large, sparse graphs)

Still the same three points:

V1————>V10

V3————>V5

V8————>V9

One chain per vertex is all it takes, which saves a lot of memory. The picture below shows the detail:

adjacency list diagram

Here is a general template for building an adjacency list:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include<stdio.h>
#include<string.h>
int n,m;
int head[10010];// head of the list; head[i] is the index of the first edge starting at i
int headcnt;// total number of edges
struct List {
	int u,v,w;// start vertex, end vertex and weight of the edge
	int next;// index of the next edge at call time
	// that is, the index of the previous edge of the current one
} edge[10010];// the struct array that stores the edges
void add(int u,int v,int w) {
	edge[headcnt].u=u;
	edge[headcnt].v=v;
	edge[headcnt].w=w;
	// store u, v and w into the edge record
	edge[headcnt].next=head[u];
	// remember the previous edge of this one (the next one at call time)
	head[u]=headcnt++;
	// record the index of this edge, which starts at u,
	// and bump the total index
}
int main() {
	while(scanf("%d %d",&n,&m)!=EOF) {
		headcnt=0;
		memset(head,-1,sizeof(head));
		while(m--) {
			int u,v,w;
			scanf("%d %d %d",&u,&v,&w);
			add(u,v,w);// read u, v, w and store them in the list
		}
		int t;
		scanf("%d",&t);
		// find the highest-index edge starting at t and walk backwards
		// until there is no edge before the current one
		for(int i=head[t]; i!=-1; i=edge[i].next) {
			printf("%d %d\n",edge[i].v,edge[i].w);
		}
	}
	return 0;
}

Reference: How to build an adjacency list — template, and when to pick a list over a matrix

This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...