dfs 深度优先搜索

DFS 算法

思想:一直往深处走,直到找到解或者走不下去为止

#include <iostream>

using namespace std;

int n,m,p,q,nmin = 9999;

int a[51][51],book[51][51];

void dfs(int x,int y,int step){//深度优先搜索

    int next[4][2] = {{1,0},{0,1},{0,-1},{-1,0}};

    int tx,ty;

    if(x == p && y == q){

        if(step < nmin){

            nmin = step;

        }

        return;

    }

    //计算下一个目标的坐标

    for(int k=0;k<=3;k++){

        tx = x + next[k][0];

        ty = y + next[k][1];

        if(tx > n || ty >m || tx < 1 || ty <1)

            continue;

        if(a[tx][ty] == 0 && book[tx][ty] == 0){

            book[tx][ty] = 1;

            dfs(tx,ty,step+1);

            book[tx][ty] = 0;

        }

    }

    return;

}

int main(){

    int startx,starty;

    cin>>n>>m;

    for(int i=1;i<=n;i++){

        for(int j=1;j<=m;j++){

            cin>>a[i][j];

        }

    }

    cin>>startx>>starty>>p>>q;

    book[startx][starty] = 1;

    dfs(startx,starty,0);

    cout<<nmin<<endl;

    return 0;

}

posted @ 2018-03-19 18:56  兔子兔子0125  阅读(311)  评论(0编辑  收藏  举报