Data structure Review "graph" __ data structure

Source: Internet
Author: User
Tags data structures in degrees min

first, the basic terminology


Figure: Consists of a poor, non-empty point set and a set of edges, which is simply written in G (V,e);

Vertex: The vertex in the graph;


No map: There is no direction for each edge of the graph;

Directed graphs: Each side of the graph has a direction;


No edge: The Edge is no direction, write as (A, B)

Forward Edge: Side is directional, write as <a,b>

Having an edge also becomes an arc; the beginning vertex is called the arc tail, and the ending vertex is called the arc head;


Simple diagram: There is no diagram pointing to its own edge, there is no two duplicate edges;


Non-direction full graph: There is an image of an edge between each vertex;

There is a direction complete graph: There are two non-reciprocal graphs between each vertex, opposite sides;


Sparse graphs: graphs with few edges relative to vertices;

Dense graphs: A lot of graphs on the side;


Weight: The edges in the graph may have a weight, in order to distinguish the length of the edges;

NET: a graph with weights;


Degree: The number of edges connected to a particular vertex;

Out degrees, degrees: for the concept of a graph, the number of edges that this vertex is the starting point, and the number of edges that this vertex is the end point, in degrees;


Ring: The same path as the first vertex and the last vertex;

Simple ring: A ring with no repeating vertices after the first vertex and the last vertex are removed;


Connect graph: Any two vertices are connected to each other diagram;

Maximal connectivity sub-graph: Contains possibly many vertices (must be connected), that is, cannot find another vertex, so that this vertex can connect to any vertex of this maximal connectivity sub-graph;

Connected components: The number of maximal connected sub-graphs;

Strong connectivity diagram: This is the concept of a forward graph, representing any two vertices, a, a, so that a can be connected to the B,b can also be connected to a diagram;


Spanning Tree: n vertices, n-1 edges, and ensuring that n vertices are interconnected (no loops);

Minimum spanning tree: the sum of the weights of the edges of this tree is the smallest of all spanning trees;


AOV Network: node represents the network of activities;

AOE Net: The net of the duration of the activity;


second, the storage structure of graphs


1. adjacency Matrix


Maintains a two-dimensional array, Arr[i][j] represents an edge of I to J, or 1 if there is an edge between two vertices, otherwise 0;

Maintains a one-dimensional array that stores vertex information, such as the name of a vertex;

The following figure is a general graph of direction:


Note: If we want to see the nodes that are adjacent to the VI node, we only need to traverse arr[i];


The following figure shows the adjacency matrix notation for graphs with weights:

Disadvantage: The adjacency matrix representation is unreasonable for sparse graphs, because it is too wasteful;


2. adjacency table


If the diagram is a general figure, the following figure:


If the net, that is, the sideband has the value, the following figure:



3. Cross-linked list

For the directed graph only, it is suitable for calculating the degree and the degree of penetration;

Vertex nodes:

Edge Junction:

Benefit: The time complexity of the creation is the same as the adjacency list, but it is possible to calculate both the in and out degrees; 4. adjacency Multiple Tables

The adjacency table is a good choice if we are simply manipulating the nodes, but if we want to delete an edge in the adjacency table, we need to delete the four vertices (because there is no graph);

In the adjacency multiple table, only need to delete a node, you can complete the deletion of the edge, it is more convenient;

Therefore, the adjacency multiple table is suitable for the operation of deleting edges;

There is no difference between vertex nodes and adjacency tables, and the edge table nodes are shown below:


Like what:


5. Array of Edge sets

Suitable for the operation of the edge in turn;

Storage edge information, as shown in the following figure:



Third, the graph of the traversal
DFS

Thought: Traverse deep, if can not go deep, then back to the moon;

Like what:


	/**
	 * O (v+e) */
	@Test public
	void DFS () {for
		(int i = 0; i < g.nodes.length; i++) {
			if (!visit Ed[i]) {
				dfs_traverse (g, i);

	}} private void Dfs_traverse (GRAPH2 g, int i) {
		visited[i] = true;
		System.out.println (i);
		Edgenode node = g.nodes[i].next;
		while (node! = null) {
			if (!visited[node.idx]) {
				dfs_traverse (g, NODE.IDX);
			}
			node = node.next;
		}
	}

BFS

Thought: Traversal of all neighboring nodes;

	/**
	 * O (v+e) */
	@Test public
	void BFS () {
		arraylist<integer> list = new Arraylist<integer > ();
		for (int i = 0; i < g.nodes.length; i++) {
			if (!visited[i]) {
				Visited[i] = true;
				List.add (i);
				System.out.println (i);
				while (!list.isempty ()) {
					int k = list.remove (0);
					Edgenode current = G.nodes[k].next;
					while (current = null) {
						if (!visited[current.idx]) {
							Visited[current.idx] = true;
							System.out.println (CURRENT.IDX);
							List.add (CURRENT.IDX);
							
						}
						current = Current.next;}}}}
	


Four, the smallest spanning tree
Prim
Adjacency matrix storage;

	/**
	 * Time complexity O (n^2)
	 * Applies to dense graphs */
	@Test public
	Void Prim () {
		int cost[] = new int[9];
		int pre[] = new int[9];
		
		for (int i=0;i<g1.vertex.length;i++) {
			cost[i] = G1.adjmatrix[0][i];
		}
		Cost[0] = 0;
		
		for (int i=1;i<g1.vertex.length;i++) {
			int min = 65536;
			int k = 0;
			for (int j=1;j<g1.vertex.length;j++) {
				if (cost[j]!=0&&cost[j]<min) {
					min = cost[j];
					K = j;
				}
			}
			Cost[k] = 0;
			System.out.println (pre[k]+ "," +k);
			for (int j=1;j<g1.vertex.length;j++) {
				if (Cost[j]!=0&&g1.adjmatrix[k][j]<cost[j]) {
					pre[j] = k;
					COST[J] = G1.adjmatrix[k][j];}}}
	

krustral Edge set array storage;

	/**
	 * Time complexity: O (Eloge)
	 * for sparse graphs */
	@Test public
	void Krustral () {
		edge[] edges = Initedges ();
		int parent[] = new int[9];
		for (int i=0;i<edges.length;i++) {
			edge edge = edges[i];
			int m = find (Parent,edge.begin);
			int n = find (parent,edge.end);
			if (m!=n) {
				parent[m] = n;
				System.out.println (m+ "," +n);
	}}} private static int Find (int[] parent, int f) {
		while (Parent[f] > 0) {
			f = parent[f];
		}
		return f;
	}

Five, Shortest path

Dijkstra Algorithm
Adjacency matrix storage;

	O (n^2)
	@Test public
	void Dijkstra () {
		int distance[] = new int[9];
		int pre[] = new int[9];
		Boolean finished[] = new boolean[9];
		Finished[0] = true;
		for (int i=0;i<9;i++) {
			distance[i] = G1.adjmatrix[0][i];
		}
		int k = 0;
		for (int i=1;i<9;i++) {
			int min = 65536;
			for (int j=0;j<9;j++) {
				if (!finished[j]&&distance[j]<min) {
					min = distance[j];
					K = j;
				}
			}
			Finished[k] = true;
			System.out.println (pre[k]+ "," +k);
			for (int j=1;j<9;j++) {
				if (!finished[j]&& (Min+g1.adjmatrix[k][j]) <distance[j]) {
					distance[ J] = Min+g1.adjmatrix[k][j];
					PRE[J] = k;}}}
	

FloydUse: (1) adjacency matrix: storage diagram;

	/**
	 * O (n^3)
	 * Find the distance between any vertices *
	 /
	@Test public
	void Floyd (Graph1 g) {
		int i, j, K;
		int length = G.vertex.length;
		int dist[][] = new Int[length][length];
		int pre[][] = new Int[length][length];
		for (i = 0; i < g.vertex.length; i++) {for
			(j = 0; J < G.vertex.length; J + +) {
				pre[i][j] = j;
				DIST[I][J] = G.adjmatrix[i][j];
			}
		}
		for (i = 0, i < length; i++) {for
			(j = 0; J < G.vertex.length; J + +) {for
				(k = 0; k < g.vertex.length; k++) {
					if (Dist[i][j] > Dist[i][k] + dist[k][j]) {
						dist[i][j] = Dist[i][k] + dist[k][j];
						PRE[I][J] = pre[i][k];
		}}} System.out.println ();
	}

Six, topological sort

Using Data structures:

(1) Stack: used to store the node in the degree of 0;

(2) Variant adjacency list: As the storage structure of the graph; the vertex node of this adjacency list also needs to hold the attribute of the in-degree;

/**
* O (n+e) */
private static String Topologicalsort (Graph2 G2) {
		stack<integer> s = new Stack <Integer> ();
		int count = 0;
		for (int i=0;i<g2.nodes.length;i++) {
			if (g2.nodes[i].indegree==0) {
				s.push (i);
			}
		}
		while (!s.isempty ()) {
			int value = S.pop ();
			System.out.println (value+ ",");
			count++;
			Edgenode node = g2.nodes[value].next;
			while (node!=null) {
				g2.nodes[node.idx].indegree--;
				if (g2.nodes[node.idx].indegree==0) {
					s.push (NODE.IDX);
				}
				node = node.next;
			}
			
		}
		if (count<g2.nodes.length) {
			return "error";
		}
		return "OK";
	}


The key path uses the data structure: (1) The Variant adjacency list: the same topological sort; (2) Variable: LTV represents the latest start time for an event, the ETV indicates the earliest start time of the event, and the Ete represents the earliest start time of the activity;

	O (n+e) @Test public void Criticalpath () {stack<integer> Stack = Topological_etv ();
		int length = Stack.size ();
		if (stack==null) {return;
			} else{INT[]LTV = new Int[length];
			for (int i=0;i<stack.size (); i++) {Ltv[i] = etv[stack.size ()-1];
				}//Calculate LTV while (!stack.isempty ()) {int top = Stack.pop () from the last start of the topology sort;
				Edgenode current = G.nodes[top].next;
					while (current!=null) {int idx = CURRENT.IDX;
					The latest occurrence is to take all activities in the earliest if ((Ltv[idx]-current.weight) <ltv[top]) {ltv[top] = ltv[idx]-current.weight;
			}}} int ete = 0;
			int LTE = 0;
				for (int j=0;j<length;j++) {edgenode-current = G.nodes[j].next;
					while (current!=null) {int idx = CURRENT.IDX;
					Ete = Etv[j];
					LTE = Ltv[idx]-current.weight; if (Ete==lte) {//Is critical Path}}}}} private stack<integer> Topological_etv () {stack&lt
		;integer> Stack2 = new stack<integer> (); Stack<integer>staCk1 = new stack<integer> ();
			for (int i=0;i<g.nodes.length;i++) {if (g.nodes[i].indegree==0) {stack1.add (i);
		}} etv[] = new Int[g.nodes.length];
		int count = 0;
			while (!stack1.isempty ()) {int top = Stack1.pop ();
			count++;
			
			Stack2.push (top);
			Edgenode current = G.nodes[top].next;
				while (current!=null) {int idx = CURRENT.IDX;
				if ((--g.nodes[idx].indegree) ==0) {Stack1.push (IDX);
				} if ((Etv[top]+current.weight) >etv[idx]) {ETV[IDX] = etv[top]+current.weight;
			} current = Current.next;
		}} if (count<g.nodes.length) {return null;
	} return Stack2; }




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.