Undirected graph-depth-first and breadth-first algorithms are extremely applied.

Source: Internet
Author: User

Undirected graph-depth-first and breadth-first algorithms are extremely applied.

First, we will introduce the second part of the Algorithms website.AlgorithmsThis book provides online courses.

In addition, this course on algorithms shown on Coursera is also very good.

 

Several Representation Methods of an image:

This method (Data Structure) is used to represent the graph. This includes the following two requirements: (1) suitable space (2) Fast Implementation of the instance method

There are three options:

(1) set of edges:

Simple but does not meet the second condition-to implement an adjacent table, you must traverse all the edges in the graph.

(2) adjacent matrix:

The use of a Boolean value of V proves that space is not satisfied.

(3) adjacent list:

Use an array list of vertex indexes. Each element in the list is a list of vertex adjacent to the vertex.

Because the preceding method is flexible, the following data structure can be defined to represent a Graph object in the case of an adjacent list.

Public class Graph {private readonly int verticals; // Number of vertices private int edges; // Number of edges private List <int> [] adjacency; // vertex join list public Graph (int vertical) {this. verticals = vertical; this. edges = 0; adjacency = new List <int> [vertical]; for (int v = 0; v <vertical; v ++) {adjacency [v] = new List <int> () ;}} public int GetVerticals () {return verticals;} public int GetEdges () {return edges ;} public void AddEdge (int verticalStart, int verticalEnd) {adjacency [verticalStart]. add (verticalEnd); adjacency [verticalEnd]. add (verticalStart); edges ++;} public List <int> GetAdjacency (int vetical) {return adjacency [vetical];}
Deep Priority Algorithm

Before talking about deep priority algorithms, let's take a look at the maze Exploration issues. The following is the correspondence between a maze and a graph:

Each intersection point in the maze represents a vertex in the graph, and each channel corresponds to one edge.

You can use the Tr é maux rope Exploration Method to explore the maze. That is:

  • Put a rope behind you
  • Place a rope to mark the access traffic point and channel in each accessed place
  • When you encounter a place that has been accessed, roll back to a place that has not been accessed before along the rope:

The figure is as follows:

The following is a small animation of maze exploration:

Deep Priority Search Algorithm simulates maze exploration. In actual graph processing algorithms, we usually separate the Graph Representation and processing logic. The overall design mode of the algorithm is as follows:

  • Create a Graph object
  • Transmits a Graph object to a Graph algorithm to process an object, such as a Paths object.
  • Then, query the processed results to obtain information.

We can see that the dfs method is recursively called, and a marked [] Mark array is maintained to determine whether the node has been accessed before the call.

Depth-first Algorithm Description: when accessing a vertex

1. Mark it as accessed;

2. recursively access all of its unlabeled neighbor vertices.

Public class DepthFirstSearch {private bool [] marked; // record whether the vertex is marked with private int count; // record the number of queries private DepthFirstSearch (Graph g, int v) {marked = new bool [g. getVerticals ()]; dfs (g, v);} private void dfs (Graph g, int v) {marked [v] = true; count ++; foreach (int vertical in g. getAdjacency (v) {if (! Marked [vertical]) dfs (g, vertical) ;}} public bool IsMarked (int vertical) {return marked [vertical];} public int Count () {return count ;}}

The simplest way to test an algorithm is to find a simple example.

Algorithm Application:

Connectivity. Given a graph, the answer is "are two given vertices connected ?" Or "how many connected subgraphs are in the graph ?"

Search for Path. Given a graph and a starting point, the system answers, "Is there a path from s to the given destination vertex v? If yes, find this path ."

Detection ring. Is the given graph a non-circular graph?

Dual-color Problem. Can we use two colors to color all vertices of a graph so that the colors of any side and even a vertex are different? This problem is equivalent to: Is this a bipartite graph?

 

Deep priority path Query

With this foundation, we can implement path query based on depth priority. To implement path query, we must define a variable to record the path we have found.

Therefore, based on the above, we define an edgesTo variable to record all the records of the vertices to s backward. Unlike recording only the records from the current node to the Start Node, we recordPath from each node to the Start Node. To complete this day's task, by setting edgesTo [w] = v, we record the edge from v to w. In other words, v-w is the last side that reaches w from s. EdgesTo [] is actually a tree pointing to its parent node.

Note that the Code only maintains an edgTo Array Based on the previous algorithm and saves the path with Stack.

Public class DepthFirstPaths {private bool [] marked; // record whether the dfs has accessed private int [] edgesTo; // record the last vertex private int s to the current node; // start point of the Search: public DepthFirstPaths (Graph g, int s) {marked = new bool [g. getVerticals ()]; edgesTo = new int [g. getVerticals ()]; this. s = s; dfs (g, s);} private void dfs (Graph g, int v) {marked [v] = true; foreach (int w in g. getAdjacency (v) {if (! Marked [w]) {edgesTo [w] = v; dfs (g, w) ;}} public bool HasPathTo (int v) {return marked [v];} public Stack <int> PathTo (int v) {if (! HasPathTo (v) return null; Stack <int> path = new Stack <int> (); for (int x = v; x! = S; x = edgesTo [x]) {path. Push (x) ;}path. Push (s); return path ;}}

 

The black line indicates that all the paths from the specified point to the origin 0 are recorded by edgeTo [], which can be seen on the right,

It is actually a tree, where the root is the origin, and the path from each subnode to the root is the path from the origin to the subnode.

It is a simple example of a deep-priority search algorithm.

 

 

 

Connected Component

The API is as follows:

The implementation of CC uses the marked [] array to find a vertex as the starting point for deep Priority Search in each connected component. The parameter called for Recursive deep search for the first time is vertex 0, marking all vertices connected to 0. Then, the for loop in the constructor looks for each unlabeled vertex and recursively calls dfs to mark all its adjacent vertices. In addition, it uses an array id [] indexed by vertex to associate the vertex in the same connected component with the identifier of the connected component. This array makes the implementation of the connected () method very simple.

Public class CC {private boolean [] marked; private int [] id; private int count; public CC (Graph g) {marked = new boolean [g. getVertexCount ()]; id = new int [g. getVertexCount ()]; for (int s = 0; s <g. getVertexCount (); s ++) {if (! Marked [s]) {dfs (g, s); count ++ ;}} private void dfs (Graph g, int v) {marked [v] = true; id [v] = count; for (int w: g. adj (v) if (! Marked [w]) dfs (g, w);}/** is v connected to w? */public boolean connected (int v, int w) {return id [v] = id [w];}/** identifier of the connected component of v */public int id (int v) {return id [v];}/* Number of connected components */public int count () {return count ;}

 

Detection ring

/*** Is the given graph without a ring chart? * detect a self-ring: If there is no self-ring, there is no parallel edge */public class Cycle {private boolean [] marked; private boolean hasCycle; public Cycle (Graph g) {marked = new boolean [g. getVertexCount ()]; for (int I = 0; I <g. getVertexCount (); I ++) if (! Marked [I]) dfs (g, I, I);} private void dfs (Graph g, int v, int u) {marked [v] = true; for (int w: g. adj (v) if (! Marked [w]) dfs (g, w, v); // If w is not marked, perform recursive deep search from w, use the parent node of w as the second parameter else if (w! = U) hasCycle = true; // If w is marked, w must be the same as the parent node if no ring exists, otherwise, it indicates whether or not the Ring}/** contains the ring */public boolean hasCycle () {return hasCycle ;}

 

Dual-color Problem

/*** Two-color problem: Can we use two colors to color all vertices of an image so that the colors of the two endpoints on any side are different? * Equivalent to: Determining whether a bipartite Graph is used */public class TwoColor {private boolean [] marked; private boolean [] color; private boolean isColorable; public TwoColor (Graph g) {isColorable = true; marked = new boolean [g. getVertexCount ()]; color = new boolean [g. getVertexCount ()]; for (int I = 0; I <g. getVertexCount (); I ++) // traverses all vertices if (! Marked [I]) dfs (g, I); // deep search without mark} private void dfs (Graph g, int v) {marked [v] = true; // mark for (int w: g. adj (v) // traverse the adjacent table if (! Marked [w]) {// if it is not marked with color [w] =! Color [v]; // the color of the current w node is set to a different color from that of the parent node dfs (g, w ); // continue deep search for the current node} else if (color [w] = color [v]) {// if it has been marked, check whether the color is the same as that of the parent node. isColorable = false; // if the color is the same, it is not a bipartite graph}/** whether it is a bipartite graph */public boolean isBipartite () {return isColorable ;}

 

 

Breadth-first algorithm

We usually pay more attention to the single-source shortest path problem, that isGiven a graph and a source S, is there a path from s to the given fixed point v? If so, find the shortest (here the shortest is defined as the minimum number of edges)

The depth-first algorithm places unaccessed nodes in a stack), Although the stack is not explicitly written in the code aboveRecursion indirectly utilizes recursive heap to implement this principle.

Unlike the depth priority algorithm,Breadth First is to put all unaccessed nodes into the queue.. The main principle is:

First, add the start point to the queue, and then repeat the steps until the queue is empty:

1. Take the next vertex V in the queue and mark it

2. Add all unlabeled vertices adjacent to v to the queue.

Breadth First searches for paths in ascending distance.

class BreadthFirstSearch{    private bool[] marked;    private int[] edgeTo;    private int sourceVetical;//Source vertical    public BreadthFirstSearch(Graph g, int s)    {        marked=new bool[g.GetVerticals()];        edgeTo=new int[g.GetVerticals()];        this.sourceVetical = s;        bfs(g, s);    }    private void bfs(Graph g, int s)    {        Queue<int> queue = new Queue<int>();        marked[s] = true;        queue.Enqueue(s);        while (queue.Count()!=0)        {            int v = queue.Dequeue();            foreach (int w in g.GetAdjacency(v))            {                if (!marked[w])                {                    edgeTo[w] = v;                    marked[w] = true;                    queue.Enqueue(w);                }            }        }    }    public bool HasPathTo(int v)    {        return marked[v];    }    public Stack<int> PathTo(int v)    {        if (!HasPathTo(v)) return null;        Stack<int> path = new Stack<int>();        for (int x = v; x!=sourceVetical; x=edgeTo[x])        {            path.Push(x);        }        path.Push(sourceVetical);        return path;    }}

Algorithm Application: Shortest Path

 

Summary:

Both deep-Priority Search and breadth-Priority Search store the start point in the data structure and repeat the steps until the data structure is cleared:

1. Take the next vertex and mark it

2. Add all adjacent and unlabeled vertices of v to the data structure.

The difference between the two algorithms lies only in the data structure.Obtain the rule of the next vertex (breadth first is the first vertex to be added, and depth first is the last vertex to be added for depth first search ).

 

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.