HBU将n∗m的教学区分成不同专业的教学与实验范围,为了简单省力,惠国惠民,相同专业的地方总是紧挨着的,上下左右相邻的属于同一个连通域,现在想知道,总共有多少专业?
输入格式:
第一行两个正整数,n,m,代表教学区宽和长;
接下来一个n*m矩阵,仅包含数字,表示专业分布。
输出格式:
一个正整数,专业总数。
输入样例:
在这里给出一组输入。例如:
4 4
1122
1222
3111
3333
输出样例:
在这里给出相应的输出。例如:
4
数据范围
n≤1000,m≤1000
思路:经典的dfs或者bfs搜索连通块个数
#include<bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define endl '\n'
#define rep(i,a,n) for (int i = a; i < n; i ++ )
#define repn(i,a,n) for (int i = a; i <= n; i ++ )
#define pb push_back
#define IOS ios::sync_with_stdio(false); cin.tie(0);cout.tie(0);
typedef long long ll;
typedef pair<int,int> PII;
ll gcd(ll a,ll b) { return b ? gcd(b,a % b) : a; }
int n, m;
const int N = 1010;
int g[N][N];
bool st[N][N];
int cnt;
int dx[] = {0, 1, 0, -1}, dy[] = {-1, 0, 1, 0};
void bfs(int x, int y){
st[x][y] = true;
queue<PII> q;
q.push({x,y});
int k = g[x][y];
while(!q.empty()){
auto t = q.front(); q.pop();
for (int i = 0; i < 4; i ++ ){
int a = t.x + dx[i], b = t.y + dy[i];
if(a < 1 || a > n || b < 1 || b > m || st[a][b] == true || g[a][b] != k) continue;
st[a][b] = true;
q.push({a, b});
}
}
}
int main(){
IOS;
cin >> n >> m;
repn(i, 1, n){
string s; cin >> s;
repn(j, 1, m){
g[i][j] = s[j - 1] - '0';
}
}
repn(i, 1, n)
repn(j, 1, m){
if(!st[i][j]){
bfs(i, j);
cnt ++;
}
}
cout << cnt << endl;
return 0;
}