WustOJ 1575 Gingers and Mints(快速幂 + dfs )

时间:2023-03-09 22:23:53
WustOJ 1575 Gingers and Mints(快速幂 + dfs )

1575: Gingers and Mints

Time Limit: 1 Sec  Memory Limit: 128 MB   64bit IO Format: %lld
Submitted: 24  Accepted: 13
[Submit][Status][Web Board]

Description

fcbruce
owns a farmland, the farmland has n * m grids. Some of the grids are
stones, rich soil is the rest. fcbruce wanna plant gingers and mints on
his farmland, and each plant could occupy area as large as possible. If
two grids share the same edge, they can be connected to the same area.
fcbruce is an odd boy, he wanna plant gingers, which odd numbers of
areas are gingers, and the rest area, mints. Now he want to know the
number of the ways he could plant.

Input

The first line of input is an integer T (T < 100), means there are T test cases.
For each test case, the first line has two integers n, m (0 < n, m < 100).
For next n lines, each line has m characters, 'N' for stone, 'Y' for rich soil that is excellent for planting.

Output

For each test case, print the answer mod 1000000007 in one line.

Sample Input WustOJ 1575 Gingers and Mints(快速幂 + dfs )

2
3 3
YNY
YNN
NYY
3 3
YYY
YYY
YYY

Sample Output

4
1

HINT

For the
first test case, there are 3 areas for planting. We marked them as A, B
and C. fcbruce can plant gingers on A, B, C or ABC. So there are 4 ways
to plant gingers and mints.

Source

Author

fcbruce

思路:
1.先用DFS求出联通块个数。
2.再根据数学知识 C{n,1} + C{n,3} + C{n,5} + ... = 2^(n-1) 用快速幂求出。
#include<cstdio>
#include<cstring>
using namespace std; #define maxn 200
char pic[maxn][maxn];
int vis[maxn][maxn];
int dx[] = {-,,,};
int dy[] = {,,-,};
int n,m; void dfs(int x, int y)
{
for(int i = ; i < ; i++)
{
int nx = x + dx[i];
int ny = y + dy[i];
if(!vis[nx][ny] && pic[nx][ny] == 'Y' && nx >= && nx < n && ny >= && ny < m)
{
vis[nx][ny] = ;
dfs(nx,ny);
}
}
}
int pow_mod(int a,int n,int m)
{ if(n==)
return ;
int x=pow_mod(a,n/,m);
long long ans=(long long)x*x%m;
if(n%==)
ans=ans*a%m;
return (int )ans;
} int main()
{
int t;
scanf("%d", &t);
while(t--)
{
scanf("%d%d", &n, &m);
memset(vis, , sizeof vis);
for(int i = ; i < n; i++)
scanf("%s", pic[i]);
int cnt = ;
for(int i = ; i < n; i++)
for(int j = ; j < m; j++)
{
if(!vis[i][j] && pic[i][j] == 'Y')
{
vis[i][j] = ;
cnt++;
dfs(i,j);
}
}
printf("%d\n",pow_mod(,cnt-,));
}
return ;
}