A brief summary of DFS and BFS

Source: Internet
Author: User

First is DFS, aka depth first search. Look at the name, it is the core of the idea is to search, first in a road above the end, if there is no way forward, then judge whether to reach the end, if not arrived, then back to the point of the previous.

The main points of Dfs:

1, consider what should be done now, in your current point above what you should do, how you can do. Can it be up? Can it be down?

2, the back and the same as the previous do. Recursive thought.

3, to consider the boundary, the end point and other topics given the conditions of detection. Filter out the unwanted solutions.

4, the use of appropriate data structure, to save the current point whether to walk through, save the route and so on.

Template:

void Dfs (int step)

{

Judge all your conditions, if not directly return;

For (loop in each direction)

DFS (STEP+1)

Return

}

Map "" "Record the place where you walked, recorded as 1

You can try to use the stack to hold records

#include <cstdio>#include<cstdlib>#include<ctime>#include<iostream>using namespacestd;intresult[Ten];intbook[Ten];intR=0;/*ask for nine different single-digit combinations to meet, 3-bit + 3-bit = 3-bit topic, mainly to record the Dfs template*/voidDfsintStep) {    if(Step = =7)/*simple optimization.*/    {        intsum = result[1]* -+ result[4]* -+ result[2]*Ten+ result[5]*Ten+ result[3] + result[6]; if(book[sum%Ten] ==1)            return; Sum/=Ten; if(book[sum%Ten] ==1)            return; Sum/=Ten; if(book[sum%Ten] ==1)            return; }    if(Step = =Ten)    {        if(result[1]* -+ result[4]* -+ result[2]*Ten+ result[5]*Ten+ result[3] + result[6] = = result[7]* -+ result[8]*Ten+ result[9]) {printf ("%d%d%d +%d%d%d =%d%d%d\n", result[1],result[2],result[3],result[4],result[5],result[6],result[7],result[8],result[9]); R++; }        return; }    inti;  for(i =1; I <=9; i++)    {        if(Book[i] = =0) {Result[step]=i; Book[i]=1; DFS (step+1); Book[i]=0; }    }    return;}intMain () {clock_t start,finish; Doubleduration; Start=clock (); DFS (1); cout<<"-------------------"<<r<<Endl; Finish=clock (); Duration=Double(Finish-start)/clocks_per_sec; printf ("Time used:%f ms\n\n", +*duration); return 0;}

Next is the BFS, also known as breadth-first search, he is an honest man, step by step is very practical, only the N-step can go everywhere, will walk the first n+1 step, slowly expand

Points:

1, with the queue to save the results of each step, with a field to indicate the number of steps to walk;

2, no recursion, using while loop to the final result;

3. Always note the position of the end-to-end pointer of the queue;

Template:

while (Head<tail)

{

for (Loop all directions)

{

Change the coordinates to the coordinates of now, meaning to take one step

Judging all the impossible, it's impossible to continue.

Mark has gone through

Add this traversed point and number of steps in the queue

tail++*****

}

head++*****

}

#include <cstdio>#include<cstdlib>#include<ctime>#include<iostream>using namespacestd;/*first define the direction array*//*x/y 0/-1-1/0 0/0 1/0 0/1 lower left upper right*/intway[4][2] = {                {1,0},//Right{0,1},//under{-1,0},//left{0,-1}//on                };intmap[ -][ -];intbook[ -][ -];intn,m;intHead=0;intTail=0;intflag=0;structque{intx; inty; intStpe;};structQue q[2500];intMain () {intx, y; CIN>>n>>m;  for(inti =1; I <= N; i++)    {         for(intj =1; J <= M; J + +) {cin>>Map[i][j]; }} head=1; Tail=1; q[tail].x=1; Q[tail].y=1; Q[tail].stpe=0; Tail++; book[1][1] =1; Flag=0;  while(head<tail) {         for(inti =0; I <3; i++) {x= q[head].x + way[i][0]; Y= Q[head].y + way[i][1]; if(x<1|| Y <1|| X > N | | Y >m)Continue; if(Map[x][y] = =0&& Book[x][y] = =0) {q[tail].x=x; Q[tail].y=y; Q[tail].stpe= Q[head].stpe +1; Tail++; Book[x][y]=1; }            if(x = =4&& y = =3) {printf ("--------------------%d\n", q[tail-1].STPE); return 0; }} head++; }    return 0;}

The main is to record a two-hour search template, the use of two specific search in the actual test, for the maze of the title is now sure not to be confused, after the graph of the traverse there are other, for the two kinds of search comparison choice, then write it.

A brief summary of DFS and BFS

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.