顺便附上本蒟蒻的代码,整体思想跟你一直都是BFS,我这里的起点选取比较特殊。
```cpp
#include<iostream>
#include<queue>
using namespace std;
int arr[40][40];
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};
int main()
{
queue<pair<int,int>> q;
int n;
int xx,yy;
cin >> n;
for(int i = 1;i <= n;i++)
for(int j = 1;j <= n;j++)
cin >> arr[i][j];
int flag = 0;
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= n;j++)
{
if(arr[i-1][j] && arr[i-1][j-1] && arr[i][j-1] && !arr[i][j])
{
xx = i;
yy = j;
q.push(make_pair(xx,yy));
arr[xx][yy] = 2;
flag = 1;
break;
}
}
if(flag == 1)
break;
}
while(!q.empty())
{
xx = q.front().first;
yy = q.front().second;
q.pop();
int sx,sy;
for(int i = 0;i < 4;i++)
{
sx = xx + dx[i];
sy = yy + dy[i];
if(!arr[sx][sy] && sx <= n && sx >= 1 && sy <= n && sy >= 1)
{
arr[sx][sy] = 2;
q.push(make_pair(sx,sy));
}
}
}
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= n;j++)
cout << arr[i][j] << ' ';
cout << endl;
}
return 0;
}
by Smithespics @ 2023-03-12 09:42:48
@[aciel](/user/811697)
我~~本蒟蒻~~觉得你这里的BFS函数中的判断条件有问题,如果这种情况输入的话就会导致外圈全部判定为2,输出结果错误,其次起点的选取的话要从0,0把全部的点而且程序整体的时间复杂度很高。
**输入:**
20
0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 1 1 1 1 1 0 1 1 1 1 1 1 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 1 1 1 1 0 0 0 1 1 1 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 1 1 1 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 1 1 0 0 0 0
by Smithespics @ 2023-03-12 09:44:10