为了正常的体验网站,请在浏览器设置里面开启Javascript功能!

8. 深度优先搜索

2011-06-06 31页 ppt 454KB 124阅读

用户头像

is_827241

暂无简介

举报
8. 深度优先搜索null第七讲第七讲搜索专题 深度优先(DFS)ACM算法与程序设计深度优先搜索算法(Depth-First-Search)深度优先搜索算法(Depth-First-Search)DFS是由获得计算机领域的最高奖-图灵奖的霍普克洛夫特与陶尔扬发明 DFS是搜索算法的一种。是沿着树的深度遍历树的节点,尽可能深的搜索树的分支。当节点v的所有边都己被探寻过,搜索将回溯到发现节点v的那条边的起始节点。这一过程一直进行到已发现从源节点可达的所有节点为止。如果还存在未被发现的节点,则选择其中一个作为源节点并重复以上过程,整个进程反复进...
8. 深度优先搜索
null第七讲第七讲搜索专 深度优先(DFS)ACM算法与程序设计深度优先搜索算法(Depth-First-Search)深度优先搜索算法(Depth-First-Search)DFS是由获得计算机领域的最高奖-图灵奖的霍普克洛夫特与陶尔扬发明 DFS是搜索算法的一种。是沿着树的深度遍历树的节点,尽可能深的搜索树的分支。当节点v的所有边都己被探寻过,搜索将回溯到发现节点v的那条边的起始节点。这一过程一直进行到已发现从源节点可达的所有节点为止。如果还存在未被发现的节点,则选择其中一个作为源节点并重复以上过程,整个进程反复进行直到所有节点都被访问为止。属于盲目搜索。 DFS的时间复杂度不高(为线性时间复杂度),遍历图的效率往往非常高。因此,鉴于深度优先搜索算法的强大功能以及高效性往往被研究图论问题的专家所推崇。 时间复杂度:O( );空间复杂度:O(bm);b - 分支系数 m - 图的最大深度 迷宫问题 迷宫问题 首先我们来想象一只老鼠,在一座不见天日的迷宫内,老鼠在入口处进去,要从出口出来。那老鼠会怎么走?当然可以是这样的:老鼠如果遇到直路,就一直往前走,如果遇到分叉路口,就任意选择其中的一条继续往下走,如果遇到死胡同,就退回到最近的一个分叉路口,选择另一条道路再走下去,如果遇到了出口,老鼠的旅途就算成功结束了。 深度优先搜索的基本原则:按照某种条件往前试探搜索,如果前进中遭到失败(正如老鼠遇到死胡同)则退回头另选通路继续搜索,直到找到满足条件的目标为止。 null然而要实现这样的算法,我们需要用到编程的一大利器---递归。 讲一个更具体的例子:从前有座山,山里有座庙,庙里有个老和尚,老和尚在讲故事,讲什么呢?讲:从前有座山,山里有座庙,庙里有个老和尚,老和尚在讲故事,讲什么呢?讲:从前有座山,山里有座庙,庙里有个老和尚,老和尚在讲故事,讲什么呢?讲:…………。好家伙,这样讲到世界末日还讲不玩,老和尚讲的故事实际上就是前面的故事情节,这样不断地调用程序本身,就形成了递归。万一这个故事中的某一个老和尚看这个故事不顺眼,就把他要讲的故事换成:“你有完没完啊!”,这样,整个故事也就嘎然而止了。 我们编程就要注意这一点,在适当的时候,就必须要有一个这样的和尚挺身而出,把整个故事给停下来,或者说他不再往深一层次搜索,要不,我们的递归就会因计算机栈空间大小的限制而溢出,称为stack overflow。 null顺序按数字编号顺序先后访问。那么我们怎么来保证这个顺序呢? 基本思想:从初始状态S开始,利用规则生成搜索树下一层任一个结点,检查是否出现目标状态G,若未出现,以此状态利用规则生成再下一层任一个结点,再检查是否为目标节点G,若未出现,继续以上操作过程,一直进行到叶节点(即不能再生成新状态节点),当它仍不是目标状态G时,回溯到上一层结果,取另一可能扩展搜索的分支。生成新状态节点。若仍不是目标状态,就按该分支一直扩展到叶节点,若仍不是目标,采用相同的回溯办法回退到上层节点,扩展可能的分支生成新状态,…,一直进行下去,直到找到目标状态G为止。nullBoolean visited[MAX]; Status (*VisitFunc)(int v);  //VisitFunc() 为顶点的访问函数。 void DFSTraverse(graph G,Status(*Visit)(int v)){ VisitFunc = Visit ; for( v=0;v方法
:数据规模很小,可以直接枚举所有情况,然后判断是否满足条件。 难点:循环层数不确定 怎么实现这个m重循环? :递归。nullm重循环的实现: void dfs(int deep) { if (deep > m) { //check answer } else if (deep <= m) { for (i = 1; i <= n; i++) dfs(deep + 1); } }null#include #include using namespace std; int m; int Pow(int x, int n) { int res = 1; while (n--) res *= x; return res; }nullvoid dfs(int deep, int curNum, int curSum) { if (deep > m) //类似于base case { if (curNum == curSum) printf("%d\n", curNum); } else if (deep <= m) { int start = (deep == 1); //第一位不为0 for (int i = start; i <= 9; i++) dfs(deep + 1, curNum * 10 + i, curSum + Pow(i, m)); //缩小问题规模 } }nullint main() { while (scanf("%d", &m), m) { dfs(1, 0, 0); } return 0; }深度优先搜索解决问题的框架深度优先搜索解决问题的框架void dfs(int deep, State curState) { if (deep > Max) //深度达到极限 { if (curState == target) //找到目标 { //... } } else { for (i = 1; i <= totalExpandMethod; i++) { dfs(deep + 1, expandMethod(curState, i)); } } }大逃亡 http://acm.uestc.edu.cn/ShowProblem.aspx?ProblemID=1022 大逃亡 http://acm.uestc.edu.cn/ShowProblem.aspx?ProblemID=1022 Description love8909遇到危险了!!!他被困在一个迷宫中,彷徨而无助。现在需要你来帮助他走出困境。他只能记住指定长度的指令(指令的长度由MinLen和MaxLen限定),并循环执行,而且他只会向下或向右(很奇怪吧^_^)。他在地图的左上角,你需要告诉他一个运动序列,即向下(D)或向右(R),使他能够成功走出这个图且不碰到陷阱。    如果还不明白,可以参看图片。图片1,2对应样例的第1组,图片3对应样例的第2组。 nullInput  第一行为1个整数T,示有T组测试数据 第二行为4个整数Height, Width, MinLen,MaxLen,分别表示地图的高,宽,命令序列的最小和最大长度。3 <= Height, Width <= 60, 2 <= MinLen <= MaxLen <= 35 第三行至第Height+2行为地图信息。其中'.'表示空地,'X'表示陷阱。 Output  只有一行,为命令序列(只含D, R)。 注意:如果有多解,输入命令长度最短的;依然有多解,输出字典序最小的(D的字典序比R小),数据保证一定存在一组解。 字典序:字符串从前往后依次比较,第一个字符不同的位置,字符较小的字符串字典序较小,详情参见字典。 nullSample Input 2 3 3 2 2 .X. ... X.. 5 5 2 3 ..X.X ....X ..... .XX.. XX..X Sample Output DR DRR null方法:暴力 复杂度为O(2^L),L是序列长度 D和R的顺序并不需要固定 当D和R的个数确定以后,我们枚举序列中D和R的个数,搜寻一条可走的矩形路线。 null#include #include #include #include int Height, Width, MinLen, MaxLen, sH, sW; char MAP[64][64]; bool in(int x, int y) { return x >= 0 && x < Height && y >= 0 && y < Width; } bool check(int x, int y) { while (in(x, y)) { if (MAP[x][y] == 'X') return false; x += sH; y += sW; } return true;}nullint main() { int T; scanf("%d", &T); while (T--) { scanf("%d %d %d %d", &Height, &Width, &MinLen, &MaxLen); for (int i = 0; i < Height; i++) scanf("%s", MAP[i]); bool find = false; for (int L = MinLen; !find && L <= MaxLen; L++) for (sH = L; !find && sH >= 0; sH--) find = dfs(0, 0, sH, sW = L - sH); } return 0; }nullchar res[128]; bool dfs(int x, int y, int D, int R) { if (check(x, y) == false) return false; if (D == 0 && R == 0) { res[x + y] = '\0'; printf("%s\n", res); return true; } if (D > 0) { res[x + y] = 'D'; if (dfs(x + 1, y, D - 1, R)) return true; } if (R > 0) { res[x + y] = 'R'; if (dfs(x, y + 1, D, R - 1)) return true; } return false;}null作业:与大逃亡很相似的题目 Tempter of the Bone http://acm.hdu.edu.cn/showproblem.php?pid=1010Restore Equations http://acm.uestc.edu.cn/ShowProblem.aspx?ProblemID=1145Restore Equations http://acm.uestc.edu.cn/ShowProblem.aspx?ProblemID=1145Description An interstellar expedition team has recently discovered on planet Mars some multiplication equations, which are believed to be the proof that Mars has once been the home of some intellectual species. However these equations are incomplete where some digits are missing because of the eroding power of Mars' nature. Here is one example. null One way to restore this equation is to assume the 3 missing digits are 3, 5, 3, respectively, obtaining 123 x 45 = 5535, which indicates this equation may indeed be the intellectual output of Mars' ancient habitants, rather than just some random numbers. There has been hot debate over this, because people aren't sure whether they can restore all the equations discovered on Mars, i.e. restore the missing digits such that the multiplication equation holds. As a programmer in NASA, you are assigned the task of checking if all the equations are restorable. nullInput  The first line is an integer T, number of equations to check. Next T lines each contains three non-empty strings A, B and C, separated by spaces. Each string contains digits('0'-'9') and/or asterisks '*' only, where an asterisk stands for a missing digit. No string begins with the digit '0'. Output  For each test case, output "Yes"(Quotes for clarity only) on a line if one can replace the asterisks with digits such that afterwards the numbers represented by A, B and C satisfy A x B = C. Otherwise output "No" instead. Note that an asterisk must be replaced with exactly one digit('0'-'9') and the resulting numbers A, B and C can't start with zeros(See sample input/output for more clarification). The length of string A and B are at most 3, and the length of C is at most 6. The length of each string is greater than zero. At least one '*' will be present in each equation. nullSample Input 2 12*   45   *5*5 11   11   *121 Sample Output Yes No null枚举两个乘数再检查是否满足等式。 递归搜索完成 这个题目和Google Code Jam China 2006 第二轮的500分类似。 The reverse() Algorithm A useful STL algorithm is reverse(). This algorithm reverses the order of elements in a specified sequence. reverse() takes two iterators that mark the sequence's beginning and end, respectively. Here is an example of reversing the order of a char array: null#include     #include     #include //算法头文件调用 reverse算法    string A,B,C;    int lena,lenb,lenc;    int a[3],b[3];    bool flag=false;    int main()    {  int ncase;scanf("%d",&ncase);        while(ncase--){            scanf("%s %s %s",A,B,C);               lena=A.length();            lenb=B.length();            lenc=C.length();            reverse(A.begin(),A.end());            reverse(B.begin(),B.end());            reverse(C.begin(),C.end());            for(int i=0;i<3;++i) a[i]=0,b[i]=0;            flag=false;            dfs(0);            if(flag)printf("Yes\n");            else printf("No\n");        }        return 0;}  nullvoid dfs(int n){        if(flag)return;        if(n==lena){            dfs1(0);return;        }        if(A[n]=='*')            for(int j=(n==lena-1);j<=9;++j){                a[n]=j;                dfs(n+1);            }        else{            a[n]=A[n]-'0';            dfs(n+1);        }    }    nullvoid dfs1(int n){        if(flag)return;        if(n==lenb){            check();return;        }        if(B[n]=='*'){            for(int j=(n==lenb-1);j<=9;++j){                b[n]=j;                dfs1(n+1);            }        }        else{            b[n]=B[n]-'0';            dfs1(n+1);        }    }    nullvoid check(){        int x=a[0]+a[1]*10+a[2]*100;        int y=b[0]+b[1]*10+b[2]*100;        int z=x*y;        for(int i=0;i=10) return;        if (z==C[lenc-1]-'0'||C[lenc-1]=='*') flag=true;    }   
/
本文档为【8. 深度优先搜索】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。 本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。 网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
热门搜索

历史搜索

    清空历史搜索