題目描述
一矩形陣列由數字0到9組成,數字1到9代表細胞,細胞的定義為沿細胞數字上下左右若還是細胞數字則為同一細胞,求給定矩形陣列的細胞個數。(1<=m,n<=100)?
輸入輸出格式
### 輸入格式:
輸入:整數m,n(m行,n列)
矩陣
輸出格式:
輸出:細胞的個數
輸入輸出樣例
輸入樣例#1:
4 10
0234500067
1034560500
2045600671
0000000089
輸出樣例#1:
4
思路:
暴力跑bfs,對每個非0的點進行dfs并把和它相鄰的點指派為0,統計數量即可
代碼:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<map>
#include<string>
#include<cstring>
using namespace std;
const int maxn=999999999;
const int minn=-999999999;
char a[108][108];
int n,m,ans;
inline int read() {
char c = getchar();
int x = 0, f = 1;
while(c < '0' || c > '9') {
if(c == '-') f = -1;
c = getchar();
}
while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
void dfs(int x,int y) {
if(x>n||x<1||y>m||y<1||a[x][y]=='0')
return;
a[x][y]='0';
dfs(x+1,y);
dfs(x,y+1);
dfs(x-1,y);
dfs(x,y-1);
}
int main() {
cin>>n>>m;
for(int i=1; i<=n; ++i) {
for(int j=1; j<=m; ++j) {
cin>>a[i][j];
}
}
for(int i=1; i<=n; i++) {
for(int j=1; j<=m; j++) {
if(a[i][j]!='0')
ans++,dfs(i,j);
}
}
cout<<ans;
return 0;
}
轉載于:https://www.cnblogs.com/pyyyyyy/p/dfs.html