Basic algorithms for graphs (BFS and DFS)

Source: Internet
Author: User

A graph is a flexible data structure that is typically used as a model to define relationships or connections between objects. Objects are represented by vertices ( V ), and relationships or associations between objects are represented by edges () of the graph E .
Graphs can be divided into the direction of the graph and the non-direction diagram, generally used G=(V,E) to represent the diagram. An adjacency matrix or adjacency table is often used to describe a graph.
In the basic algorithm of graph, the first need to contact is the graph traversal algorithm, according to the order of access nodes, can be divided into breadth-first search ( BFS ) and depth-first search ( DFS ).

Breadth First search (BFS)
Breadth-First search accesses all adjacent nodes of the current vertex before further traversing the vertices in the diagram.
A. First select a vertex as the starting node and dye it gray, and the remaining nodes are white.
B. Put the starting node in the queue.
C. Select a vertex from the head of the queue and find all nodes adjacent to it, place the found adjacency node in the tail of the queue, paint the visited node black, and the non-visited node is white. If the color of the vertex is gray, indicating that it has been found and placed in the queue, if the color of the vertex is white, the indication has not been found
D. Follow the same method to process the next node in the queue.
Basically it's the top of the team that turns black, gray in the queue, and white in the team.
Use a diagram to express the process as follows:

1. Initial state, starting at vertex 1, queue ={1} 2. Access 1 adjacency Vertex, 1 out of line black, 2,3 queued, queue ={2,3,} 3. Access 2 of the adjacency node, 2 out of the team, 4 enqueued, Queue ={3,4} 4. Access 3 adjacency nodes, 3 out of line, queue ={4} 5. Access 4 adjacency Nodes , 4 out of line, queue ={empty}
Breadth-first search starting from Vertex 1:

    1. Initial state, starting at vertex 1, queue ={1}
    2. Access 1 of adjacent vertices, 1 out of the team black, 2,3 enqueued, queue ={2,3,}
    3. Access 2 adjacency node, 2 out of team, 4 queue ={3,4}
    4. Access 3 adjacency node, 3 out of line, queue ={4}
    5. Access 4 adjacency node, 4 out of line, queue ={empty}
      Node 5 is not up to the point.
      The above diagram can be represented by the following adjacency matrix:
int maze[5][5] = {    { 0, 1, 1, 0, 0 },    { 0, 0, 1, 1, 0 },    { 0, 1, 1, 1, 0 },    { 1, 0, 0, 0, 0 },    { 0, 0, 1, 1, 0 }};

BFS core code is as follows:

  #include <iostream> #include <queue> #define N 5using namespace Std;int Maze[n][n] = {{0, 1, 1, 0, 0}, {0, 0, 1, 1, 0}, {0, 1, 1, 1, 0}, {1, 0, 0, 0, 0}, {0, 0, 1, 1, 0    }};int visited[n + 1] = {0,};void BFS (int start) {queue<int> Q;    Q.push (start);    Visited[start] = 1; while (!        Q.empty ()) {int front = Q.front ();        cout << front << "";        Q.pop ();                for (int i = 1; I <= N; i++) {if (!visited[i] && maze[front-1][i-1] = = 1) {                Visited[i] = 1;            Q.push (i);        }}}}int Main () {for (int i = 1; I <= N; i++) {if (visited[i] = = 1) continue;    BFS (i); } return 0;  

Depth-First search (DFS)
Depth-First search when a vertex is accessed during a search, it is necessary to recursively access all the adjacent vertices of this vertex that have not been visited.
All the nodes in the initial condition are white, select one as the starting vertex, and walk through the following steps:
A. Select the starting vertex to be shaded to indicate that it has not been accessed
B. Select one from the adjacency vertex of the vertex, continue the process (i.e., looking for adjacency nodes of the adjacency node), and go deep until a vertex has no adjacency node, then black it, indicating that it has been visited
C. Go back to the top vertex of the blackened vertex, and then find the remaining adjacency nodes of the previous vertex, continue as above, and if all the neighboring nodes have been accessed down, darken themselves and go back to the next level.
D. The previous layer continues to do the above operations, knowing that all vertices have been accessed.
This process can be expressed more clearly by graphs:

1. Initial state, starting from Vertex 1
2. End at Vertex 3 after accessing vertex-in-turn
3. From Vertex 3 back to Vertex 2, continue to access Vertex 5, and terminate at Vertex 5
4. Backtrack from vertex 5 to Vertex 2 and terminate at Vertex 2
5. Backtrack from Vertex 2 to vertex 1 and terminate at Vertex 1
6. Start Access from Vertex 4 and terminate at Vertex 4
To do a deep search starting at vertex 1:

    1. Initial state, starting from Vertex 1
    2. Ends at Vertex 3 after you have visited the vertex, in turn
    3. From Vertex 3 to Vertex 2, continue to access Vertex 5, and end at Vertex 5
    4. From Vertex 5 to Vertex 2, and ending at Vertex 2
    5. From Vertex 2 to vertex 1, and ending at vertex 1
    6. Access starts at Vertex 4 and terminates at Vertex 4

The above diagram can be represented by the following adjacency matrix:

int maze[5][5] = {    { 0, 1, 1, 0, 0 },    { 0, 0, 1, 0, 1 },    { 0, 0, 1, 0, 0 },    { 1, 1, 0, 0, 1 },    { 0, 0, 1, 0, 0 }};

The DFS core code is as follows (recursive implementation):

#include <iostream>#define N 5using namespace std;int maze[N][N] = {    { 0, 1, 1, 0, 0 },    { 0, 0, 1, 0, 1 },    { 0, 0, 1, 0, 0 },    { 1, 1, 0, 0, 1 },    { 0, 0, 1, 0, 0 }};int visited[N + 1] = { 0, };void DFS(int start){    visited[start] = 1;    for (int i = 1; i <= N; i++)    {        if (!visited[i] && maze[start - 1][i - 1] == 1)            DFS(i);    }    cout << start << " ";}int main(){    for (int i = 1; i <= N; i++)    {        if (visited[i] == 1)            continue;        DFS(i);    }    return 0;}

The non-recursive implementation is as follows, with a stack:

  #include <iostream> #include <stack> #define N 5using namespace Std;int Maze[n][n] = {{0, 1, 1, 0, 0}, {0, 0, 1, 0, 1}, {0, 0, 1, 0, 0}, {1, 1, 0, 0, 1}, {0, 0, 1, 0, 0    }};int visited[n + 1] = {0,};void DFS (int start) {stack<int> s;    S.push (start);    Visited[start] = 1;    BOOL Is_push = false;        while (!s.empty ()) {Is_push = false;        int v = s.top ();                for (int i = 1; I <= N; i++) {if (maze[v-1][i-1] = = 1 &&!visited[i]) {                Visited[i] = 1;                S.push (i);                Is_push = true;            Break            }} if (!is_push) {cout << v << "";        S.pop ();        }}}int Main () {for (int i = 1; I <= N; i++) {if (visited[i] = = 1) continue;    DFS (i); } return 0;  

Some DFS is the first to access the read to the node, and so on back when the node is no longer output, it is also possible. The difference between the algorithm and my above is that the timing of the output point is different, the thought is the same. DFS has good applications in both ring monitoring and topological sequencing.




Transferred from: HTTP://WWW.JIANSHU.COM/P/70952B51F0C8

Basic algorithms for graphs (BFS and DFS)

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.