aciel @ 2023-03-07 14:07:26
#include <iostream>
#include <queue>
using namespace std;
int n;
int a[31][31];
int v[31][31];//1表示标记
int dx[4]={0,1,0,-1};
int dy[4]={1,0,-1,0};
struct node
{
int x;
int y;
}st,tx;
queue <node> q;
int bfs(int x,int y)
{
st.x=x;
st.y=y;
v[x][y]=1;
q.push(st);
while(!q.empty())
{
st=q.front();
q.pop();
for(int i=0;i<4;i++){//四个方向
tx.x=st.x+dx[i];
tx.y=st.y+dy[i];
//此处是0 并且未访问过 未出界
if(a[tx.x][tx.y]==0&&v[tx.x][tx.y]==0&&tx.x>=0&&tx.x<=n+1&&tx.y>=0&&tx.y<=n+1){
v[tx.x][tx.y]=1;
q.push(tx);
}
}
}
}
int main()
{
cin>>n;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>a[i][j];
}
}
bfs(0,0);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(v[i][j]==0&&a[i][j]==0){
a[i][j]=2;
}
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
by Smithespics @ 2023-03-12 09:42:48
顺便附上本蒟蒻的代码,整体思想跟你一直都是BFS,我这里的起点选取比较特殊。
#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:44:10
@aciel
我本蒟蒻觉得你这里的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