https://www.luogu.com.cn/problem/P1162
这道题标签是bfs所以先拿Bfs做,但其实dfs更简单一些。
思路是把1外围的所有0都标记,然后再浏览整个数组,把所有未标记的0都置2输出即可,但是搜索有一个问题就是只能搜相连通的一片区域,如果外围1把整个图分为了几个区域,那搜索就只能搜索到一片区域,为了解决这个问题,需要给原来的数组扩充一层0,这样就不存在不连通的外围0了。
bfs思路:从一个点开始入队,把他叫做父节点,然后遍历与其相连的点,即四个方向的点-子节点,如果子节点满足条件则子节点入队作为新的父节点,浏览完所有子节点后,父节点便失去作用,此时父节点出队,继续由新的父节点来搜索。具体看代码理解
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <queue>
#include <iomanip>
using namespace std;
int n;
int arr[50][50];
int vis[50][50];
int xx[] = { -1,1,0,0 };
int yy[] = { 0,0,-1,1 };//上下左右
void bfs() {
queue<int>xq, yq;
xq.push(0), yq.push(0);//(0,0)点入队
vis[0][0] = 1;
while (!xq.empty()) {
for (int i = 0; i < 4; i++) {//枚举当前点周围四个点
int x = xq.front() + xx[i];
int y = yq.front() + yy[i];
if (x >= 0 && x <= n + 1 && y >= 0 && y <= n + 1 && !vis[x][y] && !arr[x][y]) {//如果该点在地图里值为0且没有访问过就入队
xq.push(x);
yq.push(y);
vis[x][y] = 1;
}
}
xq.pop(), yq.pop();//父节点出队
}
}
int main() {
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++)
cin >> arr[i][j];
}
bfs();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (!arr[i][j] && !vis[i][j])//值为0且未访问点置2
arr[i][j] = 2;
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
bfs理解起来不难,我们再看一下dfs怎么做,依然是之前的思路,只是换了一个搜索方法而已,显然,dfs写起来更简洁一点
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <queue>
#include <iomanip>
using namespace std;
int n;
int arr[50][50];
int vis[50][50];//标记数组
int xx[] = { -1,1,0,0 };//方向数组
int yy[] = { 0,0,-1,1 };//上下左右
void dfs(int x,int y) {
if (x<0 || x>n + 1 || y<0 || y>n + 1||vis[x][y]||arr[x][y])
return;
vis[x][y] = 1;
for (int i = 0; i < 4; i++) {
dfs(x + xx[i], y + yy[i]);
}
}
int main() {
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++)
cin >> arr[i][j];
}
dfs(0, 0);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (!arr[i][j] && !vis[i][j])
arr[i][j] = 2;
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}