The concept of graphs and some algorithms about graphs

Source: Internet
Author: User
Tags foreach data structures in degrees
first, the concept of the graph

The graph is the expansion of the tree in the algorithm, the tree is the data structure from the top down, the node has a parent node (except the root node), from top to bottom. And the figure does not have the concept of parent-child node, the nodes in the graph are equal relations, the result is more complex.

Figure g= (V, E), where v represents the vertex vertex,e represents Edge edge, and an edge is a fixed-point pair (U,v), where (u,v) ∈v.


Graph with no direction graph


The graph has the direction graph and the non-direction graph. In the graph, if (u,v) (the path that represents u to v) unicom, then (V,u) also unicom, such as "1" to "2" Unicom, "2" to "1" also unicom. But in the diagram of "1" to "2" Unicom, but "2" to "1" is not connected.

In the concept of diagrams, in addition to the concept of vertices and edges, often also involves the weight of a vertex to another vertex of the "cost", if the vertex is not connected, you can assume that the weight is infinite. If the weights are not involved, the vertex weights of the unicom can be considered to be 1.


In data structures, graphs are often represented by adjacency tables and adjacency matrices. 1. adjacency table
The graph above is the adjacency table of the graph, a node in the table corresponding to a node in the graph, the linked list behind the node is the node connected to the node.

The node typedef of the graph
struct node{
	char value;//node node *next;//points to the
	unicom node
};
//adjacency table
node adj[num];// Num is the number of graph nodes.

adjacency table Common expressions represent sparse graphs, that is, the number of edges of nodes | e| far less than | V|^2. For a forward graph, the contiguous table storage occupies a space of | v|+| e|, for the graph without direction | v|+2| e|, because each table appears two times in the adjacency table. In the storage of the dominant, but in determining whether two nodes (U,v) is connected, you must first find in the adjacency table U, traverse the chain list behind U to judge. 2. Adjacency Matrix
The image above is an adjacency matrix representation of an no-map. The adjacency matrix is a | V|x| V| Matrix Gmatr, if (u,v) Unicom, then gmatr[u][v]=1. If the graph is weighted, gmatr[u][v]= weights.
BOOL Gmatr[num][num];//num is the number of graph nodes.

It can be seen that the representation of the adjacency matrix takes up space of O (v^2), but only O (1) When judging whether two nodes are interconnected. When the graph compares the hours more the adjacency matrix is used, because it is more clear. If the graph is not weighted, a bits can be used to indicate whether the two graphs are connected to each other.
second, the algorithm of graph 1. Topology sequencingTopological sorting is a sort that is applied to a forward-free graph. For example, if you have a path of U to V (not necessarily connected) in the diagram, you appear in front of v. Topological sequencing is often used to sort between related projects. For example, in a solution, project A is completed before project B can be carried out, and engineering D relies on Engineering B and Engineering C.
Then the sort may be a B C D, or a C b d. First, the concept of "indgree" is defined, and the degree of V is the number of all (U,V) Unicom nodes, that is, how many nodes can be directly to V. Then the topological sort steps are as follows: 1, from the figure to find the one by one into the zero-in nodes, sequentially placed in the sorting queue. 2. Delete the node in the diagram and delete the edge from the node. 3, update other nodes in the degree. Repeat 1-3 until all the nodes are sorted. Code:
void Topsort ()
{for
	(int i=0;i<num;i++)
	{
		Vertex v=findindegreezero ();//find any one by one-degree zero-in points
		Putverter (v);//Place the node in the sort queue for each
		Vertex u adjanct to v//v to w node Unicom
			w.indgree--;//in degrees minus one
		}
}

2. Breadth-first traversal of graphsThe breadth-first traversal of graphs is somewhat like a hierarchical traversal of a tree, and is a hierarchical search process. Assuming the traversal from the V0 node, first traverse the point w1,w2 connected to the V0 node ..., and then traverse the point u1,u2 with W1 unicom ..., the point W2 with Q1 unicom .... In the traversal process, be careful not to iterate over a node, often after traversing a node to mark the node. Breadth-first traversal often uses queues. The steps are as follows: 1, put node v into the queue. Mark V 2, if the queue is empty then end, otherwise take out the queue header node U. 3, find the junction with U Unicom w1,w2 ..., if not traversed, then traverse, then mark, queue. Go to 2.
void BFS ()
{
	Vertex v;//First traversed node
	v.visit=true;//tag
	q.push (v);//Queue while
	(! Q.empty ())
	{
		Vertex u=pop ();
		foreach (Every critical point W of u)
		{
			w.visit=true;
			Q.push (w);}}
}

3. Depth-first traversal of graphsDepth-first traversal is the "deep" traversal diagram possible. It is assumed that from the node V0, the traversal is traversed, and the nodes v1 that are not necessarily traversed with v0 are traversed, and then the nodes v2 that are not traversed by V1 and the link are iterated. If no nodes can traverse after traversing to the VN, then the returned Oh V (n-1) then goes to the node traversal, and so on. Until all the nodes in the diagram have been traversed. You can see that the depth-first traversal of the graph can be stacked. 1. Put node v into the stack. Mark V 2, if the stack is empty then end, otherwise remove the top node of the stack U. 3. Find the W1,W2 with U-unicom and unmarked nodes ..., and merge into the stack. Go to 2.
void DFS ()
{
	Vertex v;
	V.visit=true;
	S.push (v);
	while (! S.empty ())
	{
		Vertex u=s.pop ();
		U.visit=true;
		For (each adjacency point of U W and w.visit=false)
					S.push (w);
	}
}

4. Minimum spanning treeThe minimum spanning tree is applied to the non-connected map. Spanning tree is the connection of all the nodes in the graph and the path between any one or two vertices. The minimum is the minimum of the weights of the paths that connect all vertices together. The minimum spanning tree is constructed by greedy algorithm, and the whole optimal is achieved by local optimization. G (v,e) is a non-connecting graph with a weighted function of W. A is a subset of the smallest spanning tree, initially empty, with a loop iteration, each adding an edge to a, and ensuring that a is still a subset of the smallest spanning tree after joining the edge, then the added edge is called the "safe edge." Until all the nodes are added to a, the loop ends.
Greec-mst (g,w)
{
	a=∅;//empty collection while
	a don ' t for a spanning tree does
		find A Edge (u,v) that's safe for A
  a=a∪{(U,v)};
  return A;
}
In the selection of set a and secure edge, different methods formed two minimum spanning tree algorithm: 1, Kruskal. 2, Prim. Both algorithms use a two-fork heap, the algorithm complexity is O (ELOGV), but if prim use Fibonacci heaps, its algorithm complexity can reach O (E+VLOGV). 1. Kruskal algorithmIn the Kruskal algorithm, A is a forest, the weighted value of the selection of the lowest weight of the edge, if the selected edge does not form a loop, is a safe side, add it in the growing forest.
Mst-kruskal (g,w)
{
	a=∅;//empty
	set for each V-in-v do
	 Make-set (v);//make V into sets
	sort the edges of E into Nondecre Asing ORDER by weight w//installation weights in ascending order
	for each (u,v) in E, taken in nondecreasing order by weight  
         if Find-set (u)! = Fi Nd-set (v)//find-set (v) to find the representative element of the set of V (a
          = a U {(u,v)}  
          Union (u,v)  //Merge two sets
  return A;
}
2. Prim algorithmIn the prim algorithm, the edges in a form a single tree, and each loop adds a node to a (the node with the least-weighted edge connection). In the implementation of the algorithm to use a minimum priority queue, not the nodes in the tree is placed in the minimum priority queue based on the weight key Q, for node V, the value of key[v] is a vertex connected to the tree a minimum weight, if not connected, then key[v]=∞.
Mst-prim (g,w)
{
	//Select a vertex v
	Vertex v;
	key[v]=0;
	Subtract v foreach u∈g do key[u]=∞ in the g=g-{v};//collection
		;
	q=g;//construct priority queue while
	(q!=?)
		Do U=extract-min (Q)
			foreach U∈adj[v] do
				if U∈q and W (v,u) <key[u]
				   key[u]=w (v,u)
}





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.