#include<iostream> using namespace std; const int MAXN = 30 + 5; int n; int map[MAXN][MAXN]; bool vis[MAXN][MAXN]; int dx[] = { 0, 0, 0, -1, 1}; int dy[] = { 0, 1, -1, 0, 0}; void dfs(int x, int y) { if(x >= 0 && x <= n + 1 && y >= 0 && y <= n + 1) { if(map[x][y] == 1 || map[x][y] == 3) return; else { map[x][y] = 3; for(int i = 1; i <= 4; i++) dfs(x + dx[i], y + dy[i]); } } } int main() { cin >> n; for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) cin >> map[i][j]; dfs(0, 0); for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { if(map[i][j] == 3) map[i][j] = 0; else if(map[i][j] == 0) map[i][j] = 2; } } for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { cout << map[i][j] << " "; } cout << endl; } return 0; }
以上是代码 1 , 为AC代码
#include<iostream> using namespace std; const int MAXN = 30 + 5; int n; int map[MAXN][MAXN]; bool vis[MAXN][MAXN]; int dx[] = { 0, 0, 0, -1, 1}; int dy[] = { 0, 1, -1, 0, 0}; void dfs(int x, int y) { if(x >= 1 && x <= n && y >= 1 && y <= n) { if(map[x][y] == 1 || map[x][y] == 3) return; else { map[x][y] = 3; for(int i = 1; i <= 4; i++) dfs(x + dx[i], y + dy[i]); } } } int main() { cin >> n; for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) cin >> map[i][j]; dfs(1, 1); for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { if(map[i][j] == 3) map[i][j] = 0; else if(map[i][j] == 0) map[i][j] = 2; } } for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { cout << map[i][j] << " "; } cout << endl; } return 0; }
以上为代码 2,为错误代码,只得了32 分,只有 dfs( )中 if( )里面和 dfs( )调用的参数有差别,样例都过了,但是搞不懂为什么,求解!谢谢!
代码1考虑到了围墙,代码2把围墙内的第一层作为了围墙
using namespace std;
int a[32][32],b[32][32];
int dx[5]={0,-1,1,0,0};
int dy[5]={0,0,0,-1,1};
int n,i,j;
void dfs(int p,int q){
int i;
if (p<0||p>n+1||q<0||q>n+1||a[p][q]!=0) return;
a[p][q]=1;
for (i=1;i<=4;i++) dfs(p+dx[i],q+dy[i]);
}
int main(){
cin>>n;
for (i=1;i<=n;i++)
for (j=1;j<=n;j++){
cin>>b[i][j];
if (b[i][j]0) a[i][j]=0;
else a[i][j]=2;
}
dfs(0,0);
for (i=1;i<=n;i++){
for (j=1;j<=n;j++)
if (a[i][j]0) cout<<2<<' ';
else cout<<b[i][j]<<' ';
cout<<'\n';
}
}
可供参考
可以看一下我的blog,有一篇专门讲解dfs
– Drophair 4年前@Drophair: 嗯,您能帮我解答一下吗?
– goalltheway 4年前