douhuazhenren1 @ 2024-04-25 20:15:52
#include<iostream>
using namespace std;
int n,dx[4]={1,-1,0,0},dy[4]={0,0,1,-1},a[35][35];
void NASA(int o,int p)
{
int x=o,y=p;
a[o][p]=0;
for(int i=0;i<4;i++)
{
x=x+dx[i];
y=y+dy[i];
if(x<=0 || y<=0 || x>n || y>n || a[x][y]==1)
return;
else
NASA(x,y);
}
}
int 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)
a[i][j]=2;
}
for(int i=1,j=1;i<=n;i++)
if(a[i][j]==2)//上
NASA(i,j);
for(int i=1,j=n;i<=n;i++)
if(a[i][j]==2)//下
NASA(i,j);
for(int i=1,j=1;j<=n;j++)
if(a[i][j]==2)//左
NASA(i,j);
for(int i=n,j=1;j<=n;j++)
if(a[i][j]==2)//右
NASA(i,j);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
思路大概就是先把所有都涂成2,然后从四面八方找,把四周的变成零
by xk2013 @ 2024-04-25 20:24:13
@douhuazhenren1 这题是广搜,BFS!
by maodou0902 @ 2024-04-25 20:31:26
if(x<=0 || y<=0 || x>n || y>n || a[x][y]==1)
应改为
if(x<=0 || y<=0 || x>n || y>n || a[x][y]==1 || a[x][y]==0)
因为不加
a[x][y]==0
会导致死循环 @douhuazhenren1
by douhuazhenren1 @ 2024-04-25 20:34:18
样例过了,但是只对了两个点qwq@maodou0902
by LittleL0124 @ 2024-04-25 20:41:21
#include<iostream>
using namespace std;
int n,dx[4]={1,-1,0,0},dy[4]={0,0,1,-1},a[35][35];
bool f[35][35];
void NASA(int o,int p)
{
int x=o,y=p;
a[o][p]=0;
f[o][p]=1;//判断一下是否走过
for(int i=0;i<4;i++)
{
int xs=x+dx[i];//要单独设个变量 不然量会叠加
int ys=y+dy[i];
if(xs<=0 || ys<=0 || xs>n || ys>n || a[xs][ys]==1 || f[xs][ys]==1)
continue;//每个方向都要找一遍 不能直接return
else
NASA(xs,ys);
}
}
int 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)
a[i][j]=2;
}
for(int i=1,j=1;i<=n;i++)
if(a[i][j]==2)//上
NASA(i,j);
for(int i=1,j=n;i<=n;i++)
if(a[i][j]==2)//下
NASA(i,j);
for(int i=1,j=1;j<=n;j++)
if(a[i][j]==2)//左
NASA(i,j);
for(int i=n,j=1;j<=n;j++)
if(a[i][j]==2)//右
NASA(i,j);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
by douhuazhenren1 @ 2024-04-25 20:50:15
谢谢大佬,刚刚忘记看有没有走过了@LittleL0124
by Nk96321 @ 2024-04-25 21:54:48
你这个很显然啊