1. 题目来源:算法设计与问题求解第五章第二节
2.解题思路:
利用BFS的算法,遍历所有非零点,如果他们是互相连通就把他们的邻接点,push进入queue的,然后把st数组设置为true。
#include<iostream>
#include<queue>
using namespace std;
const int N = 1000;
char g[N][N];
bool st[N][N];
int n, m;
typedef pair<int, int> PII;//换名
int res = 0;//存储答案
int dx[] = { -1,0,1,0 };
int dy[] = { 0,1,0,-1 };
void bfs(int x, int y)//bfs的模板
{
queue<PII> q;
q.push({ x,y });
st[x][y] = true;
while (!q.empty())
{
auto t = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int a = t.first + dx[i];
int b = t.second + dy[i];
if (a < 0 || b < 0 || a >= n || b >= m)continue;
if (g[a][b] == '0')continue;
if (st[a][b]) continue;
st[a][b] = true;
q.push({ a,b });
}
}
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> g[i][j];
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (g[i][j] != '0'&&!st[i][j])//遍历每个点,且这个点还没被push进入queue中
{
bfs(i, j);//将所有它的连接点的st数组全部置为true
res++;//每多一个res++;
}
}
}
cout << res;
}
3.运行代码