DFS与BFS
  • 板块学术版
  • 楼主CHIMPANCAKE
  • 当前回复5
  • 已保存回复5
  • 发布时间2022/1/6 17:49
  • 上次更新2023/10/28 12:44:56
查看原帖
DFS与BFS
548201
CHIMPANCAKE楼主2022/1/6 17:49
#include<stdio.h>
#include<cstring>
#include<queue>
using namespace std;
char map[15][15];
int dx[4]={0,0,-1,1};
int dy[4]={-1,1,0,0};
struct point
{
	int x;
	int y;
};
point n;
int count,a,b;
void bfs(int x,int y)
{
	queue<point> ok;
	ok.push({x,y});
	while(!ok.empty())
	{
		n=ok.front();
		ok.pop();
		map[n.x][n.y] = '0';
		//if(x=终点坐标x&&y=终点坐标y)
		for(int i=0;i<4;i++)
		{
			int nx=n.x+dx[i],ny=n.y+dy[i];
			if(nx>0&&nx<=a&&ny>0&&ny<=b&&map[nx][ny]!='0') ok.push({nx,ny}),map[nx][ny]='0';
		}
	}
	return ;
}
int main()
{
	scanf("%d%d",&a,&b);
	for(int i=1;i<=a;i++) scanf("%s",map[i]+1);
	for(int i=1;i<=a;i++)
	{
		for(int j=1;j<=b;j++)
		{
			if(map[i][j]!='0')
			{
				bfs(i,j);
				count++;
			}
		}
	}
	printf("%d\n",count);
	return 0;
}

这是BFS还是DFS?

水帖一个

2022/1/6 17:49
加载中...