这道题不是dfs连通块嘛?换个做法试试看?
by myEnd @ 2021-07-12 10:21:02
```
#include<bits/stdc++.h>
using namespace std;
int n,k[30][30]={1},san=0,xf[4]={-1,1,0,0},yf[4]={0,0,1,-1},l=0;
int dfs(int a,int b)
{
// cout<<a<<" "<<b<<endl;
k[a][b]=2;
for(int i=0;i<4;i++)
{
if(a+xf[i]>=0&&a+xf[i]<n&&k[a+xf[i]][b+yf[i]]==0&&b+yf[i]>=0&&b+yf[i]<n)
dfs(a+xf[i],b+yf[i]);
}
}
int main(){
cin>>n;
for(int a=0;a<n;a++)
for(int b=0;b<n;b++)
cin>>k[a][b];
cout<<endl;
for(int a=n-1;a>=0;a--)
for(int b=0;b<n;b++)
{
if(k[a][b]==1&&k[a][b+1]==0&&l==0)
{
l=1;
b++;
if(b>=n)
break;
}
if(l==1&&k[a][b]==0)
{
dfs(a,b);
for(int a=0;a<n;a++)
{
for(int b=0;b<n;b++)
cout<<k[a][b]<<" ";
cout<<endl;
}
return 0;
}
}
}
```
还过不了
by 刘卓勋 @ 2021-07-12 11:23:28
```
#include <bits/stdc++.h>
using namespace std;
int n;
char a[40][40];
char b[40][40];
bool is_touch_side(int x, int y)
{
if(x < 0) return true;
if(x >= n) return true;
if(y < 0) return true;
if(y >= n) return true;
if(a[x][y] == '1') return false;
//很重要,如果不标记走过的位置会死循环
if(b[x][y] == 1) return false;
b[x][y] = 1;
// 向左
if(is_touch_side(x - 1, y)) return true;
// 向右
if(is_touch_side(x + 1, y)) return true;
// 向上
if(is_touch_side(x, y - 1)) return true;
// 向下
if(is_touch_side(x, y + 1)) return true;
return false;
//四个方向依次判断
}
int main()
{
cin >> n;
for(int i = 0; i < n; i ++)
{
for(int j = 0; j < n; j ++)
{
cin >> a[i][j];
}
}
for(int i = 0; i < n; i ++)
{
for(int j = 0; j < n; j ++)
{
memset(b, 0, sizeof(b));
if(a[i][j] == '1')
{
cout << a[i][j] << " ";
continue;
}
//如果是一,不用判断
if(is_touch_side(i, j))
{
cout << a[i][j] << " ";
}
else
{
cout << "2 ";
}
}
cout << endl;
}
return 0;
}
```
by chenyitian @ 2021-08-08 23:04:33