这会恶心吗?
by __世界第一弱__ @ 2016-11-16 11:43:38
然而bfs和dfs都能写出来,就看lz会不会了
我写了个感染病毒版的dfs,lz参考下
```cpp
#include <iostream>
short puzzle[32][32];
void dfs(short a,short b){
if(a>=0&&b>=0&&a<=32&&b<=32){
if(puzzle[a][b]==0) puzzle[a][b]=-1;
if(puzzle[a+1][b]==0) dfs(a+1,b);
if(puzzle[a][b+1]==0) dfs(a,b+1);
if(a==0||b==0){}
else{
if(puzzle[a-1][b]==0) dfs(a-1,b);
if(puzzle[a][b-1]==0) dfs(a,b-1);
}
}
}
int main(){
short n;
std::cin>>n;
for(short i=1;i<=n;i++)
{
for(short j=1;j<=n;j++)
{
std::cin>>puzzle[i][j];
}
}
dfs(0,0);
for(short i=1;i<=n;i++)
{
for(short j=1;j<=n;j++)
{
if(puzzle[i][j]==-1) {puzzle[i][j]=0;}
else if(puzzle[i][j]==0) puzzle[i][j]=2;
std::cout<<puzzle[i][j]<<" ";
}
std::cout<<std::endl;
}
return 0;
}
```
bfs可以用queue实现,就看lz会不会了(提示用queue<short> q;和queue<short> q[30];都行
by Toxic_Obsidian @ 2016-11-17 17:47:30
哈哈,这是可以考虑到的哈哈
by caoying @ 2016-12-23 22:02:47
没关系,直接在边缘用`flood`。
```cpp
#include <iostream>
using namespace std;
const int maxn = 55;
int v[maxn][maxn];
int n;
int mi[] = {1, -1, 0, 0};
int mj[] = {0, 0, 1, -1};
void dfs(int i, int j)
{
v[i][j] = 3; //visited
for (int x = 0; x < 4; x++) {
int ii = i + mi[x];
int jj = j + mj[x];
if (ii < 0 || ii >= n || jj < 0 || jj >= n) continue; //out of range
if (v[ii][jj] == 0) dfs(ii, jj);
}
}
int main()
{
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> v[i][j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || j == 0 || i == n - 1 || j == n - 1)
if (v[i][j] == 0) {
//cout << "DFS " << i << ", " << j << " : " << v[i][j] << endl;
dfs(i, j);
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (v[i][j] == 3)
v[i][j] = 0;
else if (v[i][j] == 0)
v[i][j] = 2;
cout << v[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
by Linyxus @ 2017-01-23 20:53:05
可以开大一圈数组,然后就不怕这种情况了
by 徐大仙 @ 2017-02-10 00:42:59
真的有区别莫?
by 礼部尚书 @ 2017-04-09 16:24:19