A typical flood-fill algorithm application (BFS). Not very complex, except only 1 tip: instead of searching for new space, I keep all spaces(occupied or not) in a hash_map that gets updated in a flood-fill.
#include <vector>
#include <stack>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
#include <vector>
#include <iostream>
using namespace std; #include <ext/hash_map>
using namespace __gnu_cxx; /////////////////////////
#define gc getchar_unlocked
int read_int()
{
char c = gc();
while(c<'' || c>'') c = gc();
int ret = ;
while(c>='' && c<='') {
ret = * ret + c - ;
c = gc();
}
return ret;
}
/////////////////////////
char map[][] = {};
hash_map<int,int> hm;
void clear()
{
memset(map, , * );
}
int read_map(int x, int y) // returns ppl num
{
int ret = ;
for(int j = ; j < y; j ++)
for(int i = ; i <= x; i ++)
{
char c = gc();
if(i < x) // excluding \n
{
map[j][i] = c;
if(c == '*')
{
ret ++;
}
if(c != '#')
{
hm[j * + i] = ;
}
}
}
return ret;
} int count_room(int x, int y)
{
int ret = ; while(!hm.empty())
{
stack<int> seeds;
seeds.push(hm.begin()->first);
while(!seeds.empty())
{
int seed = seeds.top(); seeds.pop();
hm.erase(seed); int sx = seed % ;
int sy = seed / ;
map[sy][sx] = '#'; // <-
if(sx > )
{
if(map[sy][sx-] != '#') seeds.push(sy * + sx -);
}
// ->
if(sx < x)
{
if(map[sy][sx+] != '#') seeds.push(sy * + sx +);
}
// ^
if(sy > )
{
if(map[sy-][sx] != '#') seeds.push((sy - ) * + sx);
}
// v
if(sy < y)
{
if(map[sy+][sx] != '#') seeds.push((sy + ) * + sx);
}
}// inner while
ret ++;
}
return ret;
}
/////////////////////////
int main()
{
int runcnt = read_int();
while(runcnt--)
{
clear(); int y = read_int();
int x = read_int(); int ppl = read_map(x, y);
int rcnt = count_room(x, y);
printf("%.2f\n", ppl*1.0/rcnt);
} return ;
}