此题被一众大佬直呼水题,但身为小白的我还是没有写出来。
正所谓从哪里跌倒就要从哪里站起来,所以我今天就恬不知耻地来写一篇题解吧!
BFS的模板涉及到队列,queue
思路:
1、在主函数中先找到起点(起点必须是岛屿),将其坐标传入BFS函数;
2、在表示海面的二维数组中有上下左右四个方向,用方向数组表示;
3、循环每一个方向是判断这个方向的下一步是否是岛屿(也就是是否满足要求,跟马踏棋盘类似)是的话就把临时变量ans++,最后返回所有ans的最大值。
bfs基本操作:
1、用数组存储方向和地图;
2、一个变量就创建临时变量,有多个变量的话就创建临时结构体,先判断第一个变量,然后一次入队,取出队列第一个数保存至临时变量(结构体)判断,出队。
代码
#define MAX 10000
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int str[MAX][MAX] = { 0 }; //表示海面,0代表海面,1代表岛屿
int arr[4][2] = { //四个方向数组
{1,0},{-1, 0},{0,1},{0,-1}
};
struct node {
int x;
int y;
};
int maxx = 0;
void BFS(int dx,int dy)
{
int ans = 1;
queue<node>s;
node start; //临时变量
start.x = dx;
start.y = dy;
s.push(start);
str[start.x][start.y] = 0;
while (!s.empty())
{
start = s.front();
s.pop();
for (int i = 0; i < 4; i++) //起点不是岛屿就遍历后面的
{
start.x += arr[i][0]; //表示向四个方向走一步
start.y += arr[i][1];
if (str[start.x][start.y] == 1 )
{
ans++;
str[start.x][start.y] = 0;
s.push(start);
}
start.x -= arr[i][0]; //还原,还是这个点向另一个方向走
start.y -= arr[i][1];
}
maxx = max(maxx, ans);
}
}
int main()
{
int n, m; //代表m * n大小的地图,规定起点必须是陆地
scanf("%d%d", &n, &m);
int dx = 0; //定义起点
int dy = 0;
memset(str, -1, sizeof(str));
for (int i = 0; i < n; i++) //输入
{
for (int j = 0; j < m; j++)
{
char c;
cin >> c;
if (c == '#') str[i][j] = 1;
else str[i][j] = 0;
}
}
for (int i = 0; i < n; i++) //判断起点是不是陆地
{
for (int j = 0; j < m; j++)
{
if (str[i][j] == 1)
{
BFS(i, j);
}
}
}
cout << maxx << endl;
return 0;
}
希望与诸君共勉