Kujo_Jotaro2011 @ 2023-07-09 15:18:58
DFS12分求助。对第四个点
by Kujo_Jotaro2011 @ 2023-07-09 15:21:19
#include<bits/stdc++.h>
using namespace std;
char earth[1005][1005];
int vis[1005][1005];
int N;
int dfs(int x,int y){
if(vis[x][y]) return 0;
else vis[x][y] = 1;
int flag = 1;
int res = 0;
if(earth[x][y] == '#'){
if(x < N){
if(earth[x+1][y] == '.'){
flag = 0;
}
res = max(dfs(x+1,y),res);
}
if(x > 1){
if(earth[x-1][y] == '.'){
flag = 0;
}
res = max(dfs(x-1,y),res);
}
if(y < N){
if(earth[x][y+1] == '.'){
flag = 0;
}
res = max(dfs(x,y+1),res);
}
if(y > 1){
if(earth[x][y-1] == '.'){
flag = 0;
}
res = max(dfs(x,y-1),res);
}
return max(flag,res);
}else{
return 0;
}
}
int main(){
cin>>N;
for(int i = 1;i <= N;i++){
for(int j = 1;j <= N;j++){
cin>>earth[i][j];
}
}
int ans = 0;
for(int i = 1;i <= N;i++){
for(int j = 1;j <= N;j++){
ans += dfs(i,j);
}
}
cout<<ans;
return 0;
}
by Kujo_Jotaro2011 @ 2023-07-09 15:21:50
代码如上
by songsong2011 @ 2023-07-11 20:44:55
#include<bits/stdc++.h>
using namespace std;
char m[1005][1005];
int vis[1005][1005];
int N;
int dfs(int x,int y){
if(vis[x][y])return 0;
else vis[x][y]=1;
int flag=1;
int res=0;
if(m[x][y]=='#'){
if(x<N){
if(m[x+1][y]=='.')
dfs(x+1,y);
res=max(res,dfs(x+1,y));
}
if(x>1){
if(m[x-1][y]=='.')
dfs(x-1,y);
res=max(res,dfs(x-1,y));
}
if(y<N){
if(m[x][y+1]=='.')
dfs(x,y+1);
res=max(res,dfs(x,y+1));
}
if(y>1){
if(m[x][y-1]=='.')
dfs(x,y-1);
res=max(res,dfs(x,y-1));
}
return max(flag,res);
}else{
return 0;
}
}
int main(){
cin>>N;
for(int i=1;i<=N;i++){
for(int j=1;j<=N;j++){
cin>>m[i][j];
}
}
int ans=0;
for(int i=1;i<=N;i++){
for(int j=1;j<=N;j++){
ans+=dfs(i,j);
}
}
cout<<ans;
}