DFS之连通性模型 AcWing 1113. 红与黑
原题链接
算法标签
DFS Flood Fill
思路
1.找到字符’@’
2.dfs向四周搜索,直至遇到’#’,搜素后用一个数组标记
#include<bits/stdc++.h>
#define int long long
#define rep(i, a, b) for(int i=a;i<b;++i)
#define Rep(i, a, b) for(int i=a;i>b;--i)
#define x first
#define y second
#define ump unordered_map
#define pq priority_queue
using namespace std;
typedef pair<int, int> PII;
const int N=25;
int n, m;
char g[N][N];
bool st[N][N];
int dx[4]={0, 1, 0, -1}, dy[4]={1, 0, -1, 0};
inline int rd(){
int s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
return s*w;
}
void put(int x) {
if(x<0) putchar('-'),x=-x;
if(x>=10) put(x/10);
putchar(x%10^48);
}
int dfs(int xa, int ya){
int cnt=1;
st[xa][ya]=true;
rep(i, 0, 4){
int x=xa+dx[i], y=ya+dy[i];
if(x<0||x>=n||y<0||y>=m){
continue;
}
if(g[x][y]!='.'){
continue;
}
if(st[x][y]){
continue;
}
cnt+=dfs(x, y);
}
return cnt;
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
while(m=rd(), n=rd()){
rep(i, 0, n){
scanf("%s", g[i]);
}
int x, y;
bool find=false;
rep(i, 0, n){
rep(j, 0, m){
if(g[i][j]=='@'){
x=i;
y=j;
find=true;
break;
}
}
if(find){
break;
}
}
memset(st, false, sizeof st);
printf("%lld\n", dfs(x, y));
}
return 0;
}
参考文献
AcWing 1113. 红与黑(算法提高课)y总视频
原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈