Learning graph theory (i)--dfs and Bfs__dfs

Source: Internet
Author: User

First, the basic elements of the diagram
1. Vertex/node (vertex);
2. Edge (Edge), connecting two points, can be without direction can also be for the edge, you can for the right side can also be the right side;
3. Connected graph: Any two points on the diagram are connected. That is, any two points are connected by one or more edges.
4. Connected components: Maximum connected subgraph. That is ① is the subgraph of the graph; ② the subgraph is connected; ③ is the subgraph with the largest number of nodes.

Two basic traversal algorithms
Learn, reference code: https://blog.csdn.net/u011437229/article/details/53188837
The thought of Dfs and BFS is an example of image.

1, Depth first search (DFS)

Reference Blog: https://blog.csdn.net/liangzhaoyang1/article/details/51415719

Thought: As the name suggests, depth first, that is, starting from a vertex, searching down to the node adjacent to the vertex, has been searched for the node does not exist adjacent nodes, and then began to backtrack, go back to the previous node, search other paths, know to traverse all the nodes or find the solution.

Core code:
void DFS (int cur)//cur is the current point
{
if (boundary condition or condition to be judged)//condition can have multiple, that is, there are multiple if statements
{
Perform the required operations;
return;
}
Do what you need to do;
For example, if you want to search the top and bottom four directions separately when walking a picture, there is a for loop, One Direction at a time.
When you have finished doing what you should, select the node that meets the criteria to continue the search.
DFS (next node that meets the criteria);
}

Simple example
Enter n nodes, m bars, and then enter the M bar of the direction graph ,
The first two elements of the edge represent the starting node, the third value table weight,
The shortest distance from City No. 1th to N city is exported.
AC Code:

#include <iostream> #include <cstring> using namespace std; 
#define INF 999999999 #define MAXN//minpath Shortest path, because with DFS, each point to search, the search after a path, are recorded, for comparison;
Egde is declared as a two-dimensional array, representing the distance between two directional connection points (which can represent bidirectional), but is not available when the data is large;

Mark acts as a marker, labeled as a visited node; int N,M,MINPATH,EGDE[MAXN][MAXN],MARK[MAXN];
    void dfs (int cur,int dist)//current point, current distance {if (Dist>minpath)////At current point is greater than the minimum distance, the following no longer traverse return;
        if (cur==n)//has arrived at the endpoint {if (minpath>dist)///shortest distance minpath = dist;
    return; for (int i=1;i<=n;++i) {//conditions are: two points between the side, the next point has not been visited, two points is not the same point, because the same point of words do not need to judge if (Egde[cur][i]!=inf
            &&!mark[i]&&egde[cur][i]) {mark[i]=1;   DFS (I,dist+egde[cur][i]);/refresh current distance mark[i]=0;
Backtracking, because each path has to be searched again, may have repeated points}} return;
        int main () {while (cin>>n>>m&&n) {int i,j; for (int i=1; i<=n; ++i) {for (int j=1; j<=n; ++J) egde[i][j] = inf; Each side is assigned to infinity, then enter the length of the edge, then infinity is two nodes without connection egde[i][i]=0;
            The same distance is 0} int a,b;//table before and after two nodes while (m--)//input edge length {cin>>a>>b;
        cin>>egde[a][b];
        memset (Mark)//mark,0,sizeof the tag array to 0, and the header file is <cstring> mark[1]=1;
        Minpath=inf;
        DFS (1,0); 
    cout<<minpath<<endl; }
}

All in all, with DFS, you have to iterate over each point (because we don't know how many points we need to traverse to find the answer, so in the beginning, of course, we're going to go through all the points, so we need to mark the points we've visited in order to prevent the access to the points we've visited on each path. , when a path is finished, reset each marked point to unlabeled , because traversing the other path may pass through the previous path.
When using DFS to occur tle (timeout), the boundary condition is generally faulted, or there is no token causing circular access. (imagine that three points are connected to each other, and to access the three points, if there are no marked points that have already been accessed, then an endless loop) occurs (the answer error), possibly without resetting the tag.

2. Breadth First search (BFS)
Thought: Breadth, same width, that is, search all the points adjacent to the current node first, then search the next level, find the target, or stop the search when you reach the destination.
Unlike DFS, because BFS needs to iterate over all adjacent points first, it cannot be implemented by recursion, but rather by using the data structure of queues-first in first out.

Core code:
void BFS (Data_type u)
{
queue< data type > Q; Create a queue queue
Define the current state;
Q.push (U); Start the node
Visit[u]=1; Access token
while (!q.empty ())//queue exits when empty, there is already an answer or no solution
{
Now=q.front (); Take the first element of the team to expand
The order of if and for can be reversed, depending on the situation
if (Reach target condition)
{
the corresponding operation;
Return
}
Perform the required actions, and then access the points adjacent to the first element of the team;
After it is found, mark it and put the qualifying points into the queue;
The first element of the team is out of the team because it has been accessed and the required operation has been performed.
}
Return
}

Simple example:
Create a simple maze of 5x5, 0 indicates the path that can be walked, 1 means the obstacle, do not go. The
can only walk up or down four directions, please find the shortest route from upper left to lower right corner.
(the output coordinates in sequence)

#include <iostream> #include <queue> using namespace std;
    BFS instance struct path{int curx;//current coordinate int cury; int Prex;
The coordinates of the forward point of the route int prey;
}MOVE[5][5]; int maze[5][5];//Maze int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};//four different directions int vit[5][5]={0};//tag array, record node has been accessed bool Check (int x,int y)//checks to see if the node satisfies the criteria for continuing the search {if (0<=x&&x<5&&0<=y&&y<5&&!vit[
    X][y]&&!maze[x][y]) return true;
return false; void print (int x,int y)//output answer function, using DFS idea {if ((x==0) && (y==0))//Starting from Start output cout<< ' (' <<x<
    < ', ' <<y<< ') ' <<endl;
        else {//the current coordinate is not the start coordinate, then continue searching for the first coordinate of the current coordinate until the start coordinates print (Move[x][y].prex,move[x][y].prey);
        cout<< ' (' <<x<< ', ' <<y<< ') ' <<endl;
    return;
    } void BFS (int stax,int stay) {queue<path> q;
    struct path now;//current state int tx,ty;
    Move[stax][stay].curx=stax; move[stax][Stay].cury=stay;    
        Q.push (move[0][0])//Starting point team vit[0][0]=1;//is already on the team, will be accessed, marked as 1 while (!q.empty ()) {now = Q.front ();
            for (int i=0;i<4;++i)//go in four directions next to the current point {//Update node state tx=now.curx+dir[i][0];
            TY=NOW.CURY+DIR[I][1];
                if (check (tx,ty)) {//Neighbor node satisfies the situation, the first node of the node is recorded as the first node Move[tx][ty].prex=now.curx;
                Move[tx][ty].prey=now.cury;
                Vit[tx][ty]=1; Q.push (Move[tx][ty]);//Meet the Node join} if (tx==4&&ty==4)//arrive at destination {print
            (Tx,ty);
            return;
    } q.pop ()//team first element out of the team because it has been visited.
} return;
            int main () {for (int i=0;i<5;++i) for (int j=0;j<5;++j) {cin>>maze[i][j];
            Move[i][j].curx=i;
        Move[i][j].cury=j;
} BFS (0,0); }

BFS is often used to find the shortest path problem , it is based on a layer of access, a layer of nodes corresponding to the next layer of connected points, so BFS need more memory.
DFS is often used to find connectivity problems, to determine whether a graph is connected, the first way to death, and then back to the beginning of a road to go. DFS is actually similar to stacks (stack). Because it requires multiple layers of recursion, so it is easy to tle.

The above for my beginner graphics theory of content, learning process to refer to a number of blog posts, after further study after the need to modify the place again.

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.