P1451 求细胞数量
题目链接
题目思路
只需要搜索在四个方向且不为0的数字块即可
dfs和bfs都可
题目代码
bfs
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 110;
int g[N][N];
bool st[N][N];
int n, m, ans;
void bfs(int x, int y)
{
queue<PII> q;
q.push({x, y});
st[x][y] = true;
while(q.size())
{
auto t = q.front();
q.pop();
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
for(int i = 0; i < 4; i ++ )
{
int a = t.first + dx[i], b = t.second + dy[i];
if(a >= 1 && a <= n && b >= 1 && b <= m && !st[a][b] && g[a][b] != 0)
{
st[a][b] = true;
q.push({a, b});
}
}
}
}
int main()
{
cin >> n >> m;
for(int i = 1; i <= n; i ++ )
for(int j = 1; j <= m; j ++ )
{
char c;
cin >> c;
g[i][j] = c - '0';
}
int cnt = 0;
for(int i = 1; i <= n; i ++ )
{
for(int j = 1; j <= m; j ++ )
{
if(g[i][j] && !st[i][j])
{
bfs(i, j);
ans ++ ;
}
}
}
cout << ans << endl;
return 0;
}
dfs
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 110;
int g[N][N];
bool st[N][N];
int n, m, ans;
void dfs(int x, int y)
{
st[x][y] = true;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
for(int i = 0; i < 4; i ++ )
{
int a = x + dx[i], b = y + dy[i];
if(st[a][b] || g[a][b] == 0) continue;
dfs(a, b);
}
}
int main()
{
cin >> n >> m;
for(int i = 1; i <= n; i ++ )
for(int j = 1; j <= m; j ++ )
{
char c;
cin >> c;
g[i][j] = c - '0';
}
int cnt = 0;
for(int i = 1; i <= n; i ++ )
{
for(int j = 1; j <= m; j ++ )
{
if(g[i][j] != 0 && !st[i][j])
{
dfs(i, j);
ans ++ ;
}
}
}
cout << ans << endl;
return 0;
}
作者:vacilie
出处:https://www.cnblogs.com/vacilie/p/16068781.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构