先贴个题目:
以及原题链接: 1113. 红与黑 - AcWing题库https://www.acwing.com/problem/content/1115/
这题也算是裸的模板题,算法是Flood Fill。可以用dfs和bfs做。
代码如下:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
#define x first
#define y second
const int N = 30;
int w, h;
char map[N][N];
int dx[4] = {0, 0, -1, 1}, dy[4] = {-1, 1, 0, 0};
bool sign[N][N];
int bfs(PII start)
{
queue<PII> q;
int ans = 1;
sign[start.x][start.y] = true;
q.push(start);
while (q.size())
{
PII tmp = q.front();
q.pop();
for (int i = 0; i < 4; ++i)
{
int tx = tmp.x + dx[i], ty = tmp.y + dy[i];
if (tx < 0 || tx >= h || ty < 0 || ty >= w)
continue;
if (map[tx][ty] == '.' && !sign[tx][ty])
{
ans++;
sign[tx][ty] = true;
q.push(make_pair(tx, ty));
}
}
}
return ans;
}
int main()
{
while (1)
{
cin >> w >> h;
if(w==0&&h==0)
break;
memset(sign, false, sizeof(sign));
PII start;
for (int i = 0; i < h; ++i)
{
getchar();
scanf("%s", &map[i]);
}
for (int i = 0; i < h; ++i)
{
for (int j = 0; j < w; ++j)
{
if (map[i][j] == '@')
start = make_pair(i, j);
}
}
cout << bfs(start)<<endl;
}
return 0;
}
我因为后面有dfs和bfs都写的,所以这题只写了bfs版本(懒)
by————2024.4.6刷题记录