dfs求连通性,bfs求迷宫最短路

本文探讨了深度优先搜索(DFS)如何用于判断图的连通性,以及广度优先搜索(BFS)如何应用于找到迷宫中的最短路径。通过实例解析了这两种经典算法的工作原理及其在解决实际问题中的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
4 6
...WWW
.W....
......
WWWWWW
4 8
........
........
........
........
2 3
WWW
WWW
6 5
.....
....W
.....
...W.
W....
....W
*/
#include <iostream>
#include <cstdio> 
#define LOCAL
using namespace std; 

const int MAXN=105;
int M,N;
char A[MAXN][MAXN];
void dfs(int x,int y)
{
		A[x][y]='.';
		for(int dx=-1;dx<=1;++dx)
		{
			for(int dy=-1;dy<=1;++dy)
			{
				int nx=x+dx,ny=y+dy;
				if(nx>=0&&nx<M&&ny>=0&&ny<N&&A[nx][ny]=='W')	//判断合法性
					dfs(nx,ny);		//状态的转移 
			}
		}
}

int main()
{
#ifdef LOCAL
	freopen("data.in","r",stdin);
	freopen("data.out","w",stdout);
#endif
	while(cin>>M>>N)
	{
		for(int i=0;i<M;++i)
			scanf("%s",A[i]);
		int res=0;
		for(int i=0;i<M;++i)
			for(int j=0;j<N;++j)
				if(A[i][j]=='W')
					{dfs(i,j);++res;}
		cout<<res<<endl;
	}
	return 0;
}



/*
6 5
1 1 0 1 1
1 0 1 1 1
1 0 1 0 0
1 0 1 1 1
1 1 1 0 1
1 1 1 1 1
*/
#include <iostream>
#include <cstdio>
#include <queue>
#define INF 0X37373737 
#define LOCAL
using namespace std;

typedef pair<int,int> P;
queue<P> que;
const int MAXN=105,FF=10; //这样FF也是const int类型 
int maze[MAXN][MAXN];	//1表示空地,0表示障碍物
int M,N,d[MAXN][MAXN]; 
int dx[]={0,1,0,-1},dy[]={1,0,-1,0};
void bfs(int x,int y)	//x,y代表起点坐标 
{
	d[x][y]=0;	
	que.push(make_pair(x,y));
	while(!que.empty())
	{
		pair<int,int> p=que.front();que.pop();
		for(int i=0;i<4;++i)
		{
			int nx=p.first+dx[i],ny=p.second+dy[i];
			if(nx>=0&&nx<M&&ny>=0&&ny<N&&d[nx][ny]==INF&&maze[nx][ny]==1)	//判断合法性 
				{que.push(make_pair(nx,ny));d[nx][ny]=d[p.first][p.second]+1;}
		}
	}
}
 
int main()
{
#ifdef LOCAL
	freopen("data.in","r",stdin);
	freopen("data.out","w",stdout);
#endif
	while(cin>>M>>N)
	{
		for(int i=0;i<M;++i)
			for(int j=0;j<N;++j)
				{cin>>maze[i][j];d[i][j]=INF;}
		
		bfs(0,0);
		for(int i=0;i<M;++i)
		{
			for(int j=0;j<N;++j)
				cout<<d[i][j]<<' ';
			cout<<endl;
		}
	}
	return 0;
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值