BFS+SPOJ AMR11J

思路:遇到*时是不应该加进去的,因为他不应该在向四周扩展,这样就需要在处理四个方向的for循环中,也就是push之前进行处理

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
const int maxn=600;
const int INF=1000000000;
char a[maxn][maxn];
int n,m,vis[maxn][maxn];
int dx[]={0,0,-1,1};
int dy[]={-1,1,0,0};
struct node
{
    int x,y,t;
    char id;
};
void solve()
{
    queue<node> q;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
            if(a[i][j]>='a'&&a[i][j]<='z')q.push((node){i,j,0,a[i][j]});
    memset(vis,0,sizeof(vis));
    while(!q.empty())
    {
        node tmp=q.front();q.pop();
        if(a[tmp.x][tmp.y]=='*')continue;
        for(int i=0;i<4;i++)
        {
            int tx=tmp.x+dx[i];
            int ty=tmp.y+dy[i];
            if(tx<1||tx>n||ty<1||ty>m||(a[tx][ty]=='#')||(a[tx][ty]=='*'))continue;
            if(a[tx][ty]=='.')
            {
                a[tx][ty]=tmp.id;
                vis[tx][ty]=tmp.t+1;
                q.push((node){tx,ty,tmp.t+1,tmp.id});
            }
            if((tmp.t+1==vis[tx][ty])&&a[tx][ty]!=tmp.id)
                a[tx][ty]='*';
        }
    }
    for(int i=1;i<=n;i++)printf("%s\n",a[i]+1);
    printf("\n");
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++)
            scanf("%s",a[i]+1);
        solve();
    }
    return 0;
}


### C++ 中使用 BFS 和 For 循环替代 DFS 的实现 在解决网格类问题时,广度优先搜索 (BFS) 可作为深度优先搜索 (DFS) 的有效替代方案。对于岛屿等问题而言,可以利用队列来管理待访问的位置,并通过 `for` 循环迭代处理这些位置。 #### 岛屿数量问题的 BFS 解决方案 下面是一个基于 BFS 来计算岛屿数量的例子: ```cpp #include <vector> #include <queue> using namespace std; class Solution { public: int numIslands(vector<vector<char>>& grid) { if (grid.empty() || grid[0].empty()) return 0; int rows = grid.size(); int cols = grid[0].size(); int islands = 0; vector<pair<int, int>> directions{{0,-1},{-1,0},{0,1},{1,0}}; for (int r = 0; r < rows; ++r){ for (int c = 0; c < cols; ++c){ if (grid[r][c] == '1'){ ++islands; queue<pair<int, int>> q; q.push({r,c}); while (!q.empty()){ auto [row, col] = q.front(); q.pop(); // 如果当前位置已经被标记,则跳过 if(grid[row][col]=='0') continue; // 将当前陆地标记为已访问 grid[row][col]='0'; // 对四个方向上的相邻节点进行探索 for(auto& dir : directions){ int newRow = row + dir.first; int newCol = col + dir.second; // 检查边界条件以及是否是未访问过的土地 if(newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols && grid[newRow][newCol] == '1') q.push({newRow,newCol}); } } } } } return islands; } }; ``` 此代码片段展示了如何使用 BFS 方法遍历整个地图并统计岛屿的数量。每当遇到一个新的岛屿部分(即值为 `'1'`),就启动一次新的 BFS 查找过程直到该岛完全被淹没为止。在此过程中,所有属于同一座岛屿的部分都会被设置成水 (`'0'`) 以防止重复计数[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值