Diagram of JavaScript data structures and algorithms and basic knowledge of graph and graph algorithms

Source: Internet
Author: User
This article mainly introduces the JavaScript data structure and algorithm diagram and graph algorithm. This article describes the directed graph, unordered graph, simple graph, and graph traversal. For more information, see Graph Definition

A Graph is a set of vertices that have a finite number of non-empty sets and edges between vertices. It is usually expressed as G (V, E), where G represents a Graph, V is the set of vertices in graph G, and E is the set of edges in graph G.

Directed Graph

Directed edge: If the edge from vertex Vi to Vj has a direction, this edge is called a directed edge and also an Arc. Vi is called the end of the arc, and Vj is called the arc header.

Unordered Graph

Undirected Edge: If the Edge between vertex Vi and Vj has no direction, this Edge is called an undirected Edge, which is expressed by an unordered pair (Vi, Vj.

Simple Diagram

Simple graph: in a graph structure, if a vertex does not exist to its own edge and the same edge does not appear repeatedly, a simple graph is called a simple graph.

Graph class

Vertices

The first step in creating a graph class is to create a Vertex class to store vertices and edges. The function of this class is the same as that of the Node class of the linked list and binary search tree. The Vertex class has two data members: one used to identify the Vertex and the other to indicate whether the accessed Boolean value has been used. They are named label and wasVisited respectively.

The Code is as follows:


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

We save all vertices in the array. In the graph class, they can be referenced by their positions in the array.

Edge

The actual information of the graph is saved on the "edge" because they describe the structure of the graph. A parent node of a binary tree can have only two subnodes, but the graph structure is much more flexible. A vertex can have an edge or multiple sides connected to it.

We convert the edge method of the graph into an adjacent table or an array of adjacent tables. It will store an array consisting of the List of adjacent vertices

Build Diagram

The following Graph class is defined:

The Code is as follows:


Function Graph (v ){
This. vertices = v; // vertices to high
This. edges = 0;
This. adj = [];
For (var I = 0; I This. adj [I] = [];
This. adj [I]. push ('');
}
This. addEdge = addEdge;
This. toString = toString;
}


This class will record how many edges a graph represents, and use a length and the number of vertices of the graph to record the number of vertices.

The Code is 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 sub-array for each element in the array to store all adjacent vertices and initialize all elements as null strings.

Graph Traversal

Deep priority Traversal

DepthFirstSearch, also known as deep Priority Search, is short for DFS.

For example, if you want to find a key in a room, you can start from any room and find the corner, bedside table, bed, bed, wardrobe, and TV cabinet in the room, after finding all the drawers and storage cabinets, you can find the next room.

Deep Priority Search:

Deep priority search is used to access a vertex that has not been accessed, mark it as accessed, and recursively access other vertex that have not been accessed in the initial vertex's adjacent table.

Add an array for the Graph class:

The Code is as follows:


This. marked = []; // Save the accessed Vertex
For (var I = 0; I This. marked [I] = false; // Initialization is false
}

Deep priority search function:

The Code is as follows:


Function dfs (v ){
This. marked [v] = true;
// The if statement is 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 );
}
}
}
}

Extended search

Breadth-first search (BFS) is a blind search method that systematically expands and checks all nodes in the graph to find the results. In other words, it does not take into account the possible location of the result. It searches the entire graph completely until the result is found.

The breadth-first search starts from the first vertex and tries to access the vertex as close as possible, as shown in:

Its working principle is:

1. First, find the unaccessed vertex adjacent to the current vertex and add it to the list of accessed vertex and queue;
2. Extract the next vertex v and add it to the list of accessed vertices.
3. Add all unaccessed vertices adjacent to v to the queue.
The following is the definition of the extended search function:

The Code is as follows:


Function bfs (s ){
Var queue = [];
This. marked = true;
Queue. push (s); // Add to team end
While (queue. length> 0 ){
Var v = queue. shift (); // remove from the beginning
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 performing a breadth-first search, the shortest path from one vertex to another is automatically searched.

Confirm path

To find the shortest path, you need to modify the breadth-first search algorithm to record the path from one vertex to another. We need an array to store all the edges from one vertex to the next vertex, we name this array edgeTo

The Code is as follows:


This. edgeTo = []; // Add this line to the Graph class.

// Bfs Function
Function bfs (s ){
Var queue = [];
This. marked = true;
Queue. push (s); // Add to team end
While (queue. length> 0 ){
Var v = queue. shift (); // remove from the beginning
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 );
}
}
}
}

Topological Sorting Algorithm

Topological sorting sorts all vertices in the directed graph so that the directed edge points to the following vertices from the preceding vertices.
The topological sorting algorithm is similar to BFS. The difference is that the topological sorting algorithm does not immediately output accessed vertices, but accesses all adjacent vertices in the current vertex list until the list is exhausted, the current vertex is pushed into the stack.

The topological sorting algorithm is split into two functions. The first function is topSort (), which is used to set the sorting process and call an auxiliary function topSortHelper (). Then, the sorted vertex list is displayed.

The main work of the topological sorting algorithm is done in the recursive function topSortHelper (). This function marks the current vertex as accessed and recursively accesses each vertex in the current vertex neighbor table, mark These vertices as accessed. Finally, press the current vertex into the stack.

The Code is as follows:


// TopSort () function
Function topSort (){
Var stack = [];
Var visited = [];
For (var I = 0; I Visited [I] = false;
}
For (var I = 0; I If (visited [I] = false ){
This. topSortHelper (I, visited, stack );
}
}
For (var I = 0; 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.