Graph theory foundation - built drawing notes and organize ideas

Today, when the class Zimo_Lee said he forgot how to build Figure ...... laughing at him while writing an essay, but also sort out their own ideas.

First posted a VisuAlgo (so delicious) on the map:

This is a chart entitled to have, explain it around the start. If the graph is undirected, built on each side of an edge when you can build the reverse.


First, the adjacency matrix

The principle is simple, if the graph [i] [j] is present data x, there is an edge represents the point i j, X is right . The code should also not have to explain:

graph[100][100];
void add_edge(int from, int to, int value){
    graph[from][to] = value;
}

Adjacency matrix is well understood, the code is very simple, and in some cases will be very easy to traverse. Disadvantages are also obvious, when drawing relatively sparse when you need a lot of unnecessary space , it will cause great waste of space.

Second, the adjacency list

The sides issued the same point exists in an array. Relatively speaking, than the adjacency matrix space-saving, but also can easily traverse all sides issued the same point.

Due to the dynamic array of needs, I use the vector used to store each node.

graph [i] [cnt] = (j, x) denotes the i article cnt edges point emanating point j, the right of x. Code:

struct edge{
    int to, val;
};
vector<edge> graph[100];
void add_edge(int from, int to, int value){
    graph[from].push_back((edge){to, value});
}

Third, the adjacency list

In the entire table each element represents an edge , start, end and edge weights are stored in the element (typically with the structure). After adjacency lists after a First Optimization [] array stores each point in the first side , an increase in the structure next stored at a starting point of an edge of the same . Thus, starting from the wanted through all numbers n junction edges, as long as the use of

for(int i=first[n]; i; i=graph[i].next)  

Can, over time consistent with the adjacent table.

On the code implementation, each optimized only when the side construction first before the [from] the side next to the current, first [from] the current number to side . Code:

struct edge{
    int to, val, next;
};
edge graph[10000];
int first[100], edge_cnt = 0;
void add_edge(int from, int to, int value){
    graph[++edge_cnt] = (edge){to, value, first[from]};
    first[from] = edge_cnt;
}

The three most common way is to build graph c ++, specific analysis to select the appropriate storage structure according to the actual situation. Not the more useful the more complex structures .

Guess you like

Origin www.cnblogs.com/miserweyte/p/11469438.html