first_king @ 2023-09-07 21:54:44
我的代码:
#include <bits/stdc++.h>
using namespace std;
int dx[4]={-1,1,0,0};
int dy[4]={0,0,-1,1};
int a[1001][1001],n;
bool vis[1001][1001];
void dfs(int x,int y){
if(x<0||x>n||y<0||y>n||vis[x][y]!=0) return ;
vis[x][y]=1;
for(int i=0;i<4;i++) dfs(x+dx[i],y+dy[i]);
}
signed main(){
cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>a[i][j];
if(a[i][j]==0) vis[i][j]=0;
else vis[i][j]=2;
}
}
dfs(1,1);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(vis[i][j]==0) cout<<2<<" ";
else cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
by One_JuRuo @ 2023-09-07 21:59:51
@first_king
显然不能从 (1,1) dfs。
hack:
6
1 1 1 1 1 0
1 0 0 1 0 0
1 0 1 1 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
by first_king @ 2023-09-07 22:01:19
@One_JuRuo 能不能帮我改一下代码
by One_JuRuo @ 2023-09-07 22:01:43
@first_king 从四个角搜索应该就对了,不太清楚,可以自己去试试。
#include <bits/stdc++.h>
using namespace std;
int dx[4]={-1,1,0,0};
int dy[4]={0,0,-1,1};
int a[1001][1001],n;
bool vis[1001][1001];
void dfs(int x,int y){
if(x<0||x>n||y<0||y>n||vis[x][y]!=0) return ;
vis[x][y]=1;
for(int i=0;i<4;i++) dfs(x+dx[i],y+dy[i]);
}
signed main(){
cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>a[i][j];
if(a[i][j]==0) vis[i][j]=0;
else vis[i][j]=2;
}
}
dfs(1,1),dfs(n,n),dfs(1,n),dfs(n,1);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(vis[i][j]==0) cout<<2<<" ";
else cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
by first_king @ 2023-09-07 22:03:08
@One_JuRuo 48分
by One_JuRuo @ 2023-09-07 22:05:23
试试这个
#include <bits/stdc++.h>
using namespace std;
int dx[4]={-1,1,0,0};
int dy[4]={0,0,-1,1};
int a[1001][1001],n;
bool vis[1001][1001];
void dfs(int x,int y){
if(x<0||x>n+1||y<0||y>n+1||vis[x][y]!=0) return ;
vis[x][y]=1;
for(int i=0;i<4;i++) dfs(x+dx[i],y+dy[i]);
}
signed main(){
cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>a[i][j];
if(a[i][j]==0) vis[i][j]=0;
else vis[i][j]=2;
}
}
dfs(0,0);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(vis[i][j]==0) cout<<2<<" ";
else cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
by first_king @ 2023-09-07 22:06:46
@One_JuRuo 对了,谢谢