JavaScript data structure and algorithm diagram and graph algorithm _ basic knowledge

Source: Internet
Author: User

The definition of a diagram

Graph is composed of a set of vertices with a poor non-empty set and an edge between vertices, usually expressed as: g (v,e), where G represents a graph, V is a set of vertices in graph G, and E is a set of edges in graph G.

A direction graph

There is to the edge: if from the vertex Vi to the edge of the Vj direction, it is called this side for the side, also become arc (ARC), with ordered even <Vi,Vj> to express, Vi called arc Tail, Vj called Arc Head.

Unordered diagram

Non-directional edge: If the vertex Vi to the Vj between the side without direction, it is said that the edge is a non-directional edge (edge), with a disordered even (VI,VJ) to express.

Simple diagram

Simple diagram: In the diagram structure, if there is no vertex to its own edge, and the same edge does not recur, it is said that such a graph is a simple diagram.

Graph class

Represents a vertex

The first step in creating a diagram class is to create a vertex class to hold vertices and edges. The function of this class is the same as the node class of the linked list and binary search tree. The vertex class has two data members: A Boolean value that identifies the vertex, and another indicates whether it has been accessed. are named label and Wasvisited respectively.

Copy Code code as follows:

function Vertex (label) {
This.label = label;
}

We keep all the vertices in the array, and in the graph class, we can refer to them by their position in the array.

Represents an Edge

The actual information of the graph is stored on the "edge", because they describe the structure of the diagram. A parent node of a binary tree can have only two child nodes, but the structure of the graph is much more flexible, a vertex can have either edge or multiple edges connected to it.

We will represent the edge of the graph as an adjacency table or an array of adjacency tables. It stores an array of adjacent vertex lists of vertices

Build diagram

Define a graph class as follows:

Copy Code code as follows:

function Graph (v) {
This.vertices = V;//vertices to High
this.edges = 0;
This.adj = [];
for (var i =0;i<this.vertices;++i) {
This.adj[i] = [];
This.adj[i].push (");
}
This.addedge = Addedge;
this.tostring = toString;
}

This class records how many edges a graph represents, and uses a length and the number of vertices of the graph to record the number of vertices.
Copy Code code as follows:

function Addedge () {
This.adj[v].push (w);
This.adj[w].push (v);
this.edges++;
}

Here we use the For loop to add a child array to each element in the array to store all the adjacent vertices and initialize all the elements to an empty string.

Traversal of graphs

Depth First traversal

Depth-first traversal (Depthfirstsearch), also known as depth-first search, is referred to as DFS.

Like looking for a key in a room, no matter from which room can start, will be in the corner of the room, bedside table, bed, bed, wardrobe, TV cabinets, etc. looking for, do not let go of any one corner, when all the drawers, storage cabinets are all searched, and then look for the next room.

Depth First search:

A depth-first search is to access a vertex that has not been visited, mark it as visited, and then recursively access the other unreachable vertices in the adjacency table of the initial vertex.

To add an array to the graph class:

Copy Code code as follows:

this.marked = [];//save visited vertices
for (Var i=0;i<this.vertices;++i) {
This.marked[i] = false;//initialized to False
}

Depth-First search function:

Copy Code code as follows:

function Dfs (v) {
THIS.MARKED[V] = true;
If statements are not required here
if (This.adj[v]!= undefined) {
Print ("visited vertex:" + V);
For each (Var w in This.adj[v]) {
if (!this.marked[w]) {
This.dfs (w);
}
}
}
}

Breadth First Search

Breadth-First search (BFS) is a blind search method designed to systematically expand and examine all nodes in the diagram to find results. In other words, it does not take into account the possible location of the result, and thoroughly searches the entire picture until the result is found.

Breadth-First search starts at the first vertex, trying to access the vertices as close to it as possible, as shown in the following illustration:

Its working principle is:

1. First find the unreachable vertex adjacent to the current vertex and add it to the list of visited vertices and queues;
2. Then remove the next vertex v from the diagram and add it to the list of visited vertices
3. Finally add all the unreachable vertices adjacent to the V to the queue
The following is the definition of the breadth-first search function:

Copy Code code as follows:

function BFs (s) {
var queue = [];
This.marked = true;
Queue.push (s);//Add to Team tail
while (queue.length>0) {
var v = queue.shift ();//Remove from Team head
if (v = = undefined) {
Print ("visited vertex:" + V);
}
For each (Var w in This.adj[v]) {
if (!this.marked[w]) {
THIS.EDGETO[W] = v;
THIS.MARKED[W] = true;
Queue.push (w);
}
}
}
}

Shortest path

When you perform a breadth-first search, you automatically find the shortest path from one vertex to another

Determine path

To find the shortest path, you need to modify the breadth-first search algorithm to record the path from one vertex to another, and we need an array to hold all the sides of the next vertex from a vertex, and we'll name this array edgeto

Copy Code code as follows:

This.edgeto = [];//adds this line to the graph class

BFS function
function BFs (s) {
var queue = [];
This.marked = true;
Queue.push (s);//Add to Team tail
while (queue.length>0) {
var v = queue.shift ();//Remove from Team head
if (v = = undefined) {
Print ("visited vertex:" + V);
}
For each (Var w in This.adj[v]) {
if (!this.marked[w]) {
THIS.EDGETO[W] = v;
THIS.MARKED[W] = true;
Queue.push (w);
}
}
}
}

Topology sorting algorithm

A topology sort sorts all the vertices of a directed graph so that a directed edge points from the preceding vertex to the trailing vertex.
The topology sort algorithm is similar to BFS, and the topology sorting algorithm does not immediately output the visited vertex, but accesses all adjacent vertices in the current vertex adjacency table until the list is exhausted to push the current vertex into the stack.

The topology sorting algorithm is split into two functions, the first function is Topsort (), which is used to set up the sort process and call an auxiliary function topsorthelper (), and then display a sorted list of vertices

The topology sorting algorithm is mainly performed in the recursive function Topsorthelper (), which marks the current vertex as being accessed, and then recursively accesses each vertex in the current vertex adjacency table, marking the vertices as accessed. Finally, the current vertex is pressed into the stack.

Copy Code code as follows:

Topsort () function
function Topsort () {
var stack = [];
var visited = [];
for (var i =0;i<this.vertices;i++) {
Visited[i] = false;
}
for (var i = 0;i<this.vertices;i++) {
if (visited[i] = = False) {
This.topsorthelper (I,visited,stack);
}
}
for (var i = 0;i<stack.length;i++) {
if (Stack[i]!=undefined && stack[i]!= false) {
Print (This.vertexlist[stack[i]]);
}
}
}

Topsorthelper () function
function Topsorthelper (v,visited,stack) {
VISITED[V] = true;
For each (Var w in This.adj[v]) {
if (!visited[w]) {
This.topsorthelper (Visited[w],visited,stack);
}
}
Stack.push (v);
}

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.