基础数据结构算法_DFS and BFS

来源:互联网 发布:黑莓解网络锁软件 编辑:程序博客网 时间:2024/05/29 07:35

图的常用遍历方法无非就是BFS和DFS,这也是常用的搜索方法。

BFS全称为广度优先搜索,以广度优先,一般采用队列辅助实现。

DFS全称为深度优先搜索,以深度优先,一般采用递归实现。

这两个用途很广,比如对于优先搜索的题目,常以BFS+优先级队列的形式。

还有二分图分的匹配采用BFS比DFS效率高,以及多状态搜索也采用BFS。

下面给出一道多状态搜索的题目:

假设一个探险家被困在了地底的迷宫之中,要从当前位置开始找到一条通往迷宫出口的路径。迷宫可以用一个二维矩阵组成,有的部分是墙,有的部分是路。迷宫之中有的路上还有门,每扇门都在迷宫的某个地方有与之匹配的钥匙,只有先拿到钥匙才能打开门。请设计一个算法,帮助探险家找到脱困的最短路径。如前所述,迷宫是通过一个二维矩阵表示的,每个元素的值的含义如下 0-墙,1-路,2-探险家的起始位置,3-迷宫的出口,大写字母-门,小写字母-对应大写字母所代表的门的钥匙 
输入描述:
迷宫的地图,用二维矩阵表示。第一行是表示矩阵的行数和列数M和N后面的M行是矩阵的数据,每一行对应与矩阵的一行(中间没有空格)。M和N都不超过100, 门不超过10扇。


输出描述:
路径的长度,是一个整数

输入例子1:
5 50211101a0A010030100101111

输出例子1:
    
这个是典型的多状态访问,因为他要保证有一步回退过程,所以每个点都用二进制设立1024个状态(这是关键)。

具体采用BFS,为什么不用DFS,因为DFS递归层数太多了怕爆工作栈。

        #include<iostream>        #include<queue>        #include<cstring>        using namespace std;                typedef struct node        {        int xp,yp;        int step;        int state;}node;        char mp[105][105];        int visit[105][105][1050];        int go[4][2]={-1,0,1,0,0,-1,0,1};        int m,n;                int bfs(int x,int y)        {        queue<node> q;        q.push(node{x,y,0,0});        while(!q.empty())        {        node at=q.front();        q.pop();        if(mp[at.xp][at.yp]=='3') return at.step;for(int u=0;u<4;u++){    int a=at.xp+go[u][0],b=at.yp+go[u][1];if(a<1||a>m||b<1||b>n||mp[a][b]=='0') continue;if('A'<=mp[a][b]&&mp[a][b]<='Z'&&    !(at.state&(1<<(mp[a][b]-'A')))) continue;if(!visit[a][b][at.state]){int k=at.state;if('a'<=mp[a][b]&&mp[a][b]<='z')        k=k|(1<<(mp[a][b]-'a'));q.push(node{a,b,at.step+1,k});visit[a][b][at.state]=1; }}}return 0;}                int main(){    while(cin>>m>>n)    {    memset(visit,0,sizeof(visit));    for(int i=1;i<=m;i++)    for(int j=1;j<=n;j++)    cin>>mp[i][j];        int T=0;    for(int i=1;i<=m;i++)    {    for(int j=1;j<=n;j++)    {    if(mp[i][j]=='2')    {    visit[i][j][0]=1;    printf("%d\n",bfs(i,j));    T=1;    break;}}if(T) break;}}return 0;}

再给出一道DFS的例题,为什么不用BFS呢因为在DFS可行的情况下DFS的形式更简单一些。

1131. Subway Map (30)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

In the big cities, the subway systems always look so complex to the visitors. To give you some sense, the following figure shows the map of Beijing subway. Now you are supposed to help people with your computer skills! Given the starting position of your user, your task is to find the quickest way to his/her destination.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (< =100), the number of subway lines. Then N lines follow, with the i-th (i = 1, ..., N) line describes the i-th subway line in the format:

M S[1] S[2] ... S[M]

where M (<= 100) is the number of stops, and S[i]'s (i = 1, ... M) are the indices of the stations (the indices are 4-digit numbers from 0000 to 9999) along the line. It is guaranteed that the stations are given in the correct order -- that is, the train travels between S[i] and S[i+1] (i = 1, ..., M-1) without any stop.

Note: It is possible to have loops, but not self-loop (no train starts from S and stops at S without passing through another station). Each station interval belongs to a unique subway line. Although the lines may cross each other at some stations (so called "transfer stations"), no station can be the conjunction of more than 5 lines.

After the description of the subway, another positive integer K (<= 10) is given. Then K lines follow, each gives a query from your user: the two indices as the starting station and the destination, respectively.

The following figure shows the sample map.

Note: It is guaranteed that all the stations are reachable, and all the queries consist of legal station numbers.

Output Specification:

For each query, first print in a line the minimum number of stops. Then you are supposed to show the optimal path in a friendly format as the following:

Take Line#X1 from S1 to S2.Take Line#X2 from S2 to S3.......

where Xi's are the line numbers and Si's are the station indices. Note: Besides the starting and ending stations, only the transfer stations shall be printed.

If the quickest path is not unique, output the one with the minimum number of transfers, which is guaranteed to be unique.

Sample Input:
47 1001 3212 1003 1204 1005 1306 77979 9988 2333 1204 2006 2005 2004 2003 2302 200113 3011 3812 3013 3001 1306 3003 2333 3066 3212 3008 2302 3010 30114 6666 8432 4011 130633011 30136666 20012004 3001
Sample Output:
2Take Line#3 from 3011 to 3013.10Take Line#4 from 6666 to 1306.Take Line#3 from 1306 to 2302.Take Line#2 from 2302 to 2001.6Take Line#2 from 2004 to 1204.Take Line#1 from 1204 to 1306.Take Line#3 from 1306 to 3001.
一道比较有趣的题目,难点在于如何判断一个站点属于哪个线路,其实只用一个站点是无法判断他属于那条线路的。

但是在给点铁路线路的情况下,我们可以用两个相邻点判断,line【x】【y】表示x-y属于哪个线路。

                #include<iostream>#include<cstdio>#include<vector>#include<cstring>using namespace std;typedef struct node{int stops;vector<int> child;}node;node mp[10005];int line[10005][10005];bool visit[10005];int Begin,End,anslen,anschange;vector<int> gopath;vector<int> anspath;//arrivepoint len change transfervoid dfs(int a,int l,int c,int t){if(l>anslen) return ;//剪枝 gopath.push_back(a);visit[a]=1;if(a==End){if(l<anslen){anspath=gopath;anslen=l;anschange=c;}else if(l==anslen&&c<anschange){anspath=gopath;anschange=c;}}else{for(int i=0;i<mp[a].child.size();i++){int nex=mp[a].child[i];if(visit[nex]==0){if(t==-1||t==line[a][nex]) dfs(nex,l+1,c,line[a][nex]);else dfs(nex,l+1,c+1,line[a][nex]);}}}gopath.pop_back();visit[a]=0;}int main(){    int n,k;    scanf("%d",&n);        for(int i=0;i<=9999;i++) mp[i].stops=i;        for(int i=1;i<=n;i++)    {    int m,pre=-1,st;    scanf("%d",&m);    for(int j=1;j<=m;j++)    {    scanf("%d",&st);    if(pre!=-1)    {    mp[st].child.push_back(pre);    mp[pre].child.push_back(st);    line[st][pre]=i;    line[pre][st]=i;}pre=st;}}scanf("%d",&k);for(int i=1;i<=k;i++){memset(visit,0,sizeof(visit));gopath.clear();anslen=10000;scanf("%d%d",&Begin,&End);//arrivepoint len change transferdfs(Begin,1,0,-1);int pret=Begin,prel=line[anspath[0]][anspath[1]];printf("%d\n",anslen-1);for(int j=1;j<anspath.size();j++){if(line[anspath[j]][anspath[j-1]]!=prel){printf("Take Line#%d from %04d to %04d.\n",prel,pret,anspath[j-1]);pret=anspath[j-1];prel=line[anspath[j]][anspath[j-1]];}}printf("Take Line#%d from %04d to %04d.\n",prel,pret,anspath.back());}return 0;}


原创粉丝点击