Simple dfs

dfs(Depth_First_Search):

It is a form of graph traversal, and its specific meaning from a vertex v graph, stop traversing each v the critical point, and then began to diverge from continuing each critical point to four weeks, until you have traversed all v path communicating point, by its very nature is in fact applied a recursive thinking;

Template code:

void DFS () // parameter indicates the state of   
{  
     IF (to reach the end state)  
    {  
        ... // add meaning of the questions   
        return ;  
    }  
    IF (cross-border or is not legitimate state)  
         return ;  
     IF (special status) // pruning 
        return ;
     for (extended mode)  
    {  
        IF (extended mode achieved legal status)  
        {  
            Modify operations; // add meaning of the questions   
            marks;  
            dfs();  
            (Reduction marker);  
            // whether to restore the meaning of the questions marks  
             // If we add (restore markers) is backtracking   
        }  
 
    }  
} 

For simple applications there is dfs full array, maze, or a combination of pruning, backtracking, DP algorithms; let's introduce the specific application;

1. the DFS full array problem:

#include<iostream>
#include<string.h>
using namespace std;
int a[101],b[101];
int i,j,n;
void  print()
{
    for(i=1;i<=n;i++)
    {
        cout<<a[i]<<" ";
    }
    cout<<endl;
}
void dfs(int i)
{
    if(i==n+1)
    {
        print();
        return ;
    }
    for ( int J = . 1 ; J <= n-; J ++) // int J is each time assignment, and j, then the process will continue in a recursive ++; 
    {
         IF (B [J] == 0 )
        {
            a[i]=j;
            b[j]=1;
            dfs(i+1);
            b[j]=0;
        }
    }
}
int main ()
{
    cin>>n;
    memset(a,sizeof(a),0);
    memset(b,sizeof(b),0);
    dfs(1);
    return 0;
}

Full array dfs problem is a typical problem, due to the need to traverse all the numbers, but can not be repeated, and thus continue to diverge dfs theme fit just right, of course, for c ++ it is simpler next_permutation a full array, and this kinds of solutions full array may also be combined with the solution typically wears backtracking

n queens problem:
the key issue is that all n queens position neither peers nor the same column, the same can not diagonal, for example, the first column of the first row to put the pieces, the next line will only be two to n columns At the same time the need to place the pieces on the diagonal minus the situation, that is n * (n-1) *minus the situation on the diagonal, in fact, just add the code on the topic a judgment condition: IF (ABS (pre [X] the -X-) == ABS (pre [Y] -Y)) return to false;

 

void generate(int index)
{
    if(index==n+1)
    {
        res++;
        return;
    }
    for(int x=1;x<=n;x++)
    {
        IF (hashTable [X] == to true ) // This line is not lower sub; 
        {
             BOOL In Flag = to true ;
             for ( int pre = . 1 ; pre <index; pre ++ )
            {
                if(abs(P[pre]-x)==abs(pre-index))
                {
                    flag=false;
                    break;
                }
            }
            if(flag)
            {
            P[index]=x;
            hashTable[x]=true;
            Generate (index + . 1 ); // continue to the next column; 
            hashTable [X] = to false ; // this arrangement the end backtracking;     
            }
        } 
    }
}

 

3. maze kind of problem: For the class of problems for the maze, if seeking all possible paths on the use of dfs, and the shortest path bfs easier;

Solve the maze is in fact a graph traversal thinking, step by step divergence wayfinding, to reach the first end res ++, you can finally get all the paths.

Topic:
from s to t, .means you can walk, *means you can not go, if we can go, the output path, if you can not take the output no.

Input:

5 6
....S*
.***..
.*..*.
*.***.
.T....

Output:

....m*                                                                        
.***mm                                                                        
.*..*m                                                                        
*.***m                                                                        
.Tmmmm  

Resolution code:

#include <iostream>
#include <string>
using namespace std;
int n, m;
string maze[110];
bool vis[110][110];
bool in(int x,int y){//防止走到地图外面
    return 0<=x&&x<n&&0<=y&&y<m;
}
BOOL DFS ( int X, int Y) { // X representing lines, y for column 
    IF (Maze [X] [Y] == ' T ' ) {
         return  to true ;
    }
    VIS [X] [Y] = . 1 ; // tag has gone through the current point 
    Maze [X] [Y] = ' m ' ; // through the point marked by the characters m 
    int TX = X- . 1 , TY = Y ; // search direction 
    IF ( in (TX, TY) && Maze [TX] [TY] =! ' * ' &&! VIS [TX] [TY]) {
         IF (DFS (TX, TY)) {
             return  to true ;
        }
    }
    tx=x,ty=y-1;//
    if(in(tx,ty)&&maze[tx][ty]!='*'&&!vis[tx][ty]){
        if(dfs(tx,ty)){
            return true;
        }
    }
    tx=x+1,ty=y;//
    if(in(tx,ty)&&maze[tx][ty]!='*'&&!vis[tx][ty]){
        if(dfs(tx,ty)){
            return true;
        }
    }
    tx=x,ty=y+1;//
    if(in(tx,ty)&&maze[tx][ty]!='*'&&!vis[tx][ty]){
        if(dfs(tx,ty)){
            return true;
        }
    }
    am [x] [y] = 0 ;
    maze[x][y]='.';
    return false;
}
int main () {
     // input labyrinth map 
    CIN >> >> n- m;
     for ( int I = 0 ; I <n-; I ++ ) {
        cin >> maze[i];
    }
    int x,y;//确定起始位置
    for(int i=0;i<n;++i){
        for(int j=0;j<m;++j){
            if(maze[i][j]=='S'){
                x=i,y=j;
            }
        }
    }
    if(dfs(x,y)){
        for(int i=0;i<n;++i){
            cout<<maze[i]<<endl;
        }
    }
    else{
        cout<<"NO!"<<endl;
    }
    return 0;
}

But generally the maze and will not appear DFS, because it needs to be recorded for the maze there are too many unnecessary moves, for example, i + 1 step to the maze boundary, then step back and continue to go elsewhere is also a maze the walk, DFS is generally performed in the maze is mainly used when the shortest path, the shortest path output BFS algorithm;

 void DFS ( int X, int Y) // recursive printing 
{
     IF (X == 0 && Y == 0 ) return ;
    dfs(father[x][y].x, father[x][y].y);
//cout<<father[x][y].dir;
cout<<father[x][y].dir<<father[x][y].x<<father[x][y].y<<endl;;
}

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/lszz/p/11827027.html
dfs