BFS 算法注意事项

  • 注意题目中给的数据的范围,来确定数组的大小,要不然找超时的原因都没有用

步骤

  1. 将初始点加入到下一个搜索的队伍中去
  2. while(head<tail) 开始循环
  3. 每次循环判断周围4个点 for(int i=0;i<4;i++)
  4. 判断越界和是否走过来决定是否可以加入到队伍中去
  5. 每次for循环完毕后,都要在队伍的头中,在增加一个head++

例题

  • 最大岛屿问题
Description

一片海洋区域中有若干个岛屿,请找出其中最大的岛屿面积。
用一个包含了一些 0 和 1的非空二维数组来代表这片区域 ,其中 1 代表面积为1的土地,0 代表水。你可以假设二维矩阵的四个边缘都被水包围着。
找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为0。)

Input

第一行两个整数n m ( n <= 100 m <= 100 )
接下来输入 n行 m列 的二维数组。

Output

输出最大岛屿的面积(如果没有岛屿,则返回面积为 0)。

Sample Input

4 5
1 0 0 1 1
1 0 1 1 0
0 1 0 0 0
1 1 0 0 1

Sample Output

4

  • 答案
#include <iostream>
using namespace std;

struct note{
    int x;
    int y;
};
int nx[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};

int main()
{
    // 超时原因可能是数组太小
    int n,m,dx,dy,mm=0;
    int data[101][101];
    note que[10000];
    int head,tail;
    int area;
    cin >> n >> m;
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            scanf("%d",&data[i][j]);
        }
    }
    // 搜索
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            if(data[i][j]==1){
                data[i][j] = 0;
                head=0,tail=0;
                que[tail].x = i;
                que[tail].y = j;
                tail++;
                area = 1;
                while(head < tail){
                    for(int k=0;k<4;k++){
                        dx = que[head].x + nx[k][0];
                        dy = que[head].y + nx[k][1];
                        if(data[dx][dy]==0) continue;
                        if(dx >=0 && dy>=0 && dx < n && dy <m){
                            data[dx][dy] = 0;
                            que[tail].x = dx;
                            que[tail].y = dy;
                            tail++;
                            area++;
                        }
                    }
                    head++;
                }
                if(area>mm){
                    mm = area;
                }
            }
        }
    }
    cout << mm << endl;
    return 0;
}
发布了31 篇原创文章 · 获赞 13 · 访问量 9887

猜你喜欢

转载自blog.csdn.net/qq_43497702/article/details/103441219
今日推荐