考点:Flood Fill算法、bfs、dfs
洪水灌溉算法多用于网格题
bfs 写法:从所在位置开始,每次遍历该方格上下左右相邻的四个方格,如果未被开发,则将其入队并标记为已开发。
while 队列非空
{
取出队头 t
枚举t的4个邻格
if 格子是陆地并且未被开发
标记为已开发
入队
}
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
const int N = 25;
int w,h;
char g[N][N];
typedef pair<int,int> PII;
int bfs(int sx,int sy)
{
queue<PII> q;
q.push({sx,sy});
g[sx][sy] = '#';
int res = 0;
int dx[] = {-1,0,1,0},dy[] = {0,1,0,-1};
while(q.size())
{
auto t = q.front();
q.pop();
res ++ ;
for(int i = 0; i < 4; i ++ )
{
int x = t.first + dx[i], y = t.second + dy[i];
if(x < 0 || x >= h || y < 0 || y >= w || g[x][y] != '.') continue;
g[x][y] = '#';
q.push({x,y});
}
}
return res;
}
int main()
{
while(cin >> w >> h, w || h)
{
for(int i = 0; i < h; i ++ ) cin >> g[i];
int x,y;
for(int i = 0; i < h; i ++ )
for(int j = 0; j < w; j ++ )
if(g[i][j] == '@')
{
x = i;
y = j;
}
cout << bfs(x,y) << endl;
}
return 0;
}
dfs写法 :
dfs(x,y)
{
将(x,y)标记为已开发;
枚举(x,y)的4个邻格 ; //上右下左顺序
if 邻格可走
dfs(邻格)
}
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
const int N = 25;
int w,h;
char g[N][N];
int dfs(int x,int y)
{
int dx[] = {-1,0,1,0},dy[]={0,1,0,-1};
g[x][y] = '#';
int res = 1;
for(int i = 0; i < 4; i ++ )
{
int a = x + dx[i] , b = y + dy[i];
if(a >= 0 && a <= h && b >= 0 && b < w && g[a][b] == '.')
res += dfs(a,b);
}
return res;
}
int main()
{
while(cin >> w >> h, w || h)
{
for(int i = 0; i < h;i ++ ) cin >> g[i];
int x,y;
for(int i = 0; i < h; i ++ )
for(int j = 0; j < w; j ++ )
if(g[i][j] == '@')
{
x = i;
y = j;
}
cout << dfs(x,y) << endl;
}
return 0;
}
注:int dx[] = {-1,0,1,0},dy[]={0,1,0,-1}; 可参考 → 偏移量的使用