一个不难的BFS染色题,难点在于开空间。
题目给的范围是n*m<=1e6
如果直接在堆里开空间必须开到1e6*1e6,显然爆了,如果在栈里边开就不能再全局跑BFS,于是就用vector动态开空间。
AC代码:
/*
* @Author: hesorchen
* @Date: 2020-07-03 17:05:01
* @LastEditTime: 2020-08-11 19:34:13
* @Description: https://hesorchen.github.io/
*/
#include <map>
#include <set>
#include <list>
#include <queue>
#include <deque>
#include <cmath>
#include <stack>
#include <vector>
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define endl '\n'
#define PI acos(-1)
#define PB push_back
#define ll long long
#define INF 0x3f3f3f3f
#define mod 1000000007
#define pll pair<ll, ll>
#define lowbit(abcd) (abcd & (-abcd))
#define max(a, b) ((a > b) ? (a) : (b))
#define min(a, b) ((a < b) ? (a) : (b))
#define IOS \
ios::sync_with_stdio(false); \
cin.tie(0); \
cout.tie(0);
#define FRE \
{ \
freopen("in.txt", "r", stdin); \
freopen("out.txt", "w", stdout); \
}
inline ll read()
{
ll x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9')
{
if (ch == '-')
f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
{
x = (x << 1) + (x << 3) + (ch ^ 48);
ch = getchar();
}
return x * f;
}
//head==============================================================================
vector<char>mp[1000010];
vector<int>vis[1000010];
struct node
{
ll x, y;
}temp1;
queue<node>q;
int mov[4][2]={ 0, 1, 0, -1, 1, 0, -1, 0 };
ll n, m;
void bfs(ll x, ll y)
{
q.push(node{ x, y });
vis[x][y]=1;
while (q.size())
{
temp1=q.front();
q.pop();
ll x=temp1.x;
ll y=temp1.y;
for (int i=0;i<4;i++)
{
ll xx= x+mov[i][0];
ll yy= y+mov[i][1];
if (xx>=1&&xx<=n&&yy>=1&&yy<=m&&!vis[xx][yy]&&mp[xx][yy]=='.')
{
vis[xx][yy]=1;
q.push(node{ xx, yy });
}
}
}
}
int main()
{
cin>>n>>m;
getchar();
char temp;
for (int i=1;i<=n;i++)
{
mp[i].push_back('?');
vis[i].push_back(0);
for (int j=1;j<=m;j++)
{
scanf("%c", &temp);
mp[i].push_back(temp);
vis[i].push_back(0);
}
getchar();
}
for (int i=1;i<=n;i++)
{
if (mp[i][1]=='.'&&!vis[i][1])
{
bfs(i, 1);
}
if (mp[i][m]=='.'&&!vis[i][m])
{
bfs(i, m);
}
}
for (int j=1;j<=m;j++)
{
if (mp[1][j]=='.'&&!vis[1][j])
{
bfs(1, j);
}
if (mp[n][j]=='.'&&!vis[n][j])
{
bfs(n, j);
}
}
ll ans =0;
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
ans+=(vis[i][j]^1);
cout<<ans<<endl;
return 0;
}
/*
5 5
...#.
.##..
.#.#.
.###.
.....
*/