CppCpp @ 2024-08-25 15:52:04
代码如下:
#include <iostream>
#include <vector>
using namespace std;
typedef vector<int> vec_int32_t;
void print_color(vector<vec_int32_t>& vec, int i, int j, int old_num, int new_num){
int n = vec.size(), m = vec.at(0).size();
if (vec[i][j] != old_num) return ;
vec[i][j] = new_num;
if (i - 1 >= 0 && vec[i - 1][j] == old_num) print_color(vec, i - 1, j, old_num, new_num);
if (i + 1 < n && vec[i + 1][j] == old_num) print_color(vec, i + 1, j, old_num, new_num);
if (j - 1 >= 0 && vec[i][j - 1] == old_num) print_color(vec, i, j - 1, old_num, new_num);
if (j + 1 < m && vec[i][j + 1] == old_num) print_color(vec, i, j + 1, old_num, new_num);
return ;
}
int main(){
int n;
cin >> n;
vector<vec_int32_t> vec(n, vec_int32_t(n));
for (auto& i : vec)
for (int& j : i) cin >> j;
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
if (vec[i][j] == 0 &&
((i == 0 || i == n - 1) ||
(j == 0 || j == n - 1))){
print_color(vec, i, j, 0, -1);
}else if (vec[i][j] == 0)
print_color(vec, i, j, 0, 2);
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
if (vec[i][j] == -1) print_color(vec, i, j, -1, 0);
for (auto& i : vec){
for (int& j : i) cout << j << " ";
cout << endl;
}
return 0;
}
by jingwenhan @ 2024-08-25 16:01:52
@CppCpp AC代码
#include<bits/stdc++.h>
using namespace std;
struct p
{
int x;
int y;
int step;
};
queue<p>dl;
int n,a[40][40],v[40][40];
int dx[4]={0,1,0,-1};
int dy[4]={0,1,-1,0};
void bfs(int x,int y)
{
while(!dl.empty())
{
dl.pop();
}
p start;
start.x=x;
start.y=y;
dl.push(start);
while(!dl.empty())
{
p shou;
shou=dl.front();
dl.pop();
for(int i=0;i<=3;i++)
{
int tx=shou.x+dx[i];
int ty=shou.y+dy[i];
if(a[tx][ty]==0&&tx>0&&ty>0&&tx<=n&&ty<=n)
{
p temp;
temp.x=tx;
temp.y=ty;
dl.push(temp);
a[tx][ty]=3;
}
}
}
return;
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cin>>a[i][j];
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if((i==1||j==1||i==n||j==n)&&a[i][j]==0)
{
a[i][j]=3;
bfs(i,j);
}
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(a[i][j]==3)
{
cout<<0<<" ";
}
if(a[i][j]==0)
{
cout<<2<<" ";
}
if(a[i][j]==1)
{
cout<<1<<" ";
}
}
cout<<endl;
}
}
by jingwenhan @ 2024-08-25 16:02:47
求一下关哈
by huangtianzeC @ 2024-08-25 16:19:34
@CppCpp 你用洪水填充(DFS 和 BFS 好像都可以吧)把能走到的0标记为特殊值,再循环整个二维数组,如果该点为特殊值,输出0;否则输出原本的值。