问题
Can someone please tell me what kind of adjacency list i have to make to build a graph with appropriate nodes and links? I have to make a tree structure to define ajdacency list? Or is there another way?
Not interested in matrix now, thank you.
can i for example make an arraylist with other arralists inside every position to the other nodes of the edges to have like:
nodes {a,b,c}, connection {{a-c},{b,c}}
so i have and arraylist or my adjacency list [a[c],b[c],c[a,b]]
回答1:
An adjacency list just represent which nodes are connected to one another.
If you had graph with the following nodes 1 -4 the adjacent matrix would look like this. '1' represent a connection between nodes.
1 2 3 4
1 1 1 1 1
2 1 0 0 0
3 0 1 0 1
4 0 1 1 0
and the list would look like this. -> represents links
1 -> 1 -> 2 -> 3 -> 4
2 -> 1
3 -> 2 -> 4
4 -> 2 -> 3
Have you though about using a linked list in an array as specified above so the array would contain node 1 - 4. Then you could either have a member variable representing the connection to another node or have a separate array list within each element of the array.
回答2:
An ArrayList of ArrayLists (or more generally, a list of lists) is a good way to go, yes. It is quite a standard respresentation of adjacency lists. So your idea is good.
Also, if you know the size of the graph (number of nodes) beforehand and don't need to add nodes to it after it has been created an array of ArrayLists would also do and be somewhat more efficient.
回答3:
You could implement an adjacency list using a Dictionary
. Each key in the dictionary would represent the starting node of the edge. Each of the values would be a List
of objects, each one defining the destination node of the edge.
For example, you could store a List
of Tuples
in each key. The first item in the Tuple
would represent the destination node. The other items would define properties of the edge.
class AdjacencyList
{
Dictionary<int, List<Tuple<int, int>>> adjacencyList;
// Constructor - creates an empty Adjacency List
public AdjacencyList(int vertices)
{
adjacencyList = new Dictionary<int, List<Tuple<int, int>>>();
}
// Appends a new Edge to the linked list
public void addEdge(int startVertex, int endVertex, int weight)
{
if (!adjacencyList.ContainsKey(startVertex)) {
adjacencyList[startVertex] = new List<Tuple<int, int>>();
}
adjacencyList[startVertex].Add(new Tuple<int, int>(endVertex, weight));
}
// Removes the first occurence of an edge and returns true
// if there was any change in the collection, else false
public bool removeEdge(int startVertex, int endVertex, int weight)
{
Tuple<int, int> edge = new Tuple<int, int>(endVertex, weight);
return adjacencyList[startVertex].Remove(edge);
}
}
来源:https://stackoverflow.com/questions/10740894/adjacency-list-for-graph-build