基础数据结构算法_DFS and BFS

2 篇文章 0 订阅
1 篇文章 0 订阅
本文介绍了在复杂的城市地铁系统中,如何使用深度优先搜索(DFS)和广度优先搜索(BFS)进行路径查找。BFS通常通过队列辅助实现,适合优先搜索和二分图匹配;DFS则通过递归实现,适用于多状态搜索。文中给出了一个案例,强调在多状态搜索中,BFS优于DFS以避免工作栈溢出。同时,提供了一个地铁地图的示例,要求找到从起点到终点的最短路径,并输出最少换乘次数及最优路径。
摘要由CSDN通过智能技术生成

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

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

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

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

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

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

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


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

输入例子1:
5 5
02111
01a0A
01003
01001
01111

输出例子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:
4
7 1001 3212 1003 1204 1005 1306 7797
9 9988 2333 1204 2006 2005 2004 2003 2302 2001
13 3011 3812 3013 3001 1306 3003 2333 3066 3212 3008 2302 3010 3011
4 6666 8432 4011 1306
3
3011 3013
6666 2001
2004 3001
Sample Output:
2
Take Line#3 from 3011 to 3013.
10
Take Line#4 from 6666 to 1306.
Take Line#3 from 1306 to 2302.
Take Line#2 from 2302 to 2001.
6
Take Line#2 from 2004 to 1204.
Take Line#1 from 1204 to 1306.
Take Line#3 from 1306 to 3001.
一道比较有趣的题目,难点在于如何判断一个站点属于哪个线路,其实只用一个站点是无法判断他属于那条线路的。

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

#include<iostream>
#include<algorithm>
#include<vector>
#include<cstdio>
using namespace std;
typedef struct node {
	int u,v;
	int com;
}node;
vector<int> mp[10005];
int coms[10005][10005];
int N,K;
int be,en;

int vis[10005];
vector<node> v1,v2;
int flag,len;

void super(node &nt) {
	if(nt.v!=en || v1.size()>len) return;
	if(flag==0 || v1.size()<len) {
		v2=v1;
		flag=1;
		len=v1.size();
	}else {
		int coms1=0,coms2=0;
		int pre1=-1,pre2=-1;
		for(int i=0;i<v1.size();i++) {
			if(v1[i].com!=pre1) {
			    coms1++,pre1=v1[i].com;
			} 
			if(v2[i].com!=pre2) {
			    coms2++,pre2=v2[i].com;
			} 
		}
		if(coms1<coms2) {
			v2=v1;
		}
	}
}

void dfs(int p) {
	vis[p]=1;
	if(v1.size()<len) { //常用的剪枝技巧,不断的缩小搜索范围。 
		for(int i=0;i<mp[p].size();i++) {
			int ch=mp[p][i];
			if(vis[ch]==0) {
				node nt;
				nt.com=coms[p][ch],nt.u=p,nt.v=ch;
				v1.push_back(nt);
				super(nt);
				dfs(ch);
				v1.pop_back();
			}
		}
	}
	vis[p]=0;
}

int main() {
    scanf("%d",&N);
    int m;
    for(int i=1;i<=N;i++) {
    	scanf("%d",&m);
    	int pre=-1,now;
    	for(int j=1;j<=m;j++) {
    		scanf("%d",&now);
    		if(pre!=-1) {
    		    mp[pre].push_back(now);
				mp[now].push_back(pre);
				coms[pre][now]=i;
				coms[now][pre]=i;
			}
			pre=now;
		}
	}
	scanf("%d",&K);
	for(int i=1;i<=K;i++) {
		for(int it=0;it<=10000;it++) vis[it]=0;
		v1.clear(),v2.clear(),flag=0,len=10001;
		scanf("%d%d",&be,&en);
		dfs(be);
		if(flag==0) {
			printf("Sorry, no line is available.\n");
		}else {
			int a=be,b,c=v2[0].com;
			printf("%d\n",v2.size());
			for(int j=0;j<v2.size();j++) {
				b=v2[j].v;
				if(j==v2.size()-1||v2[j+1].com!=c) {
					printf("Go by the line of company #%d from %04d to %04d.\n",c,a,b);
					if(j!=v2.size()-1) {
						a=v2[j+1].u;
						c=v2[j+1].com;
					}
				}
			}
		}
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值