Problem:
Score : 300 points

Problem Statement

There is a grid with H rows and W columns, where each square is painted black or white.

You are given H strings S_1, S_2, ..., S_H, each of length W.
If the square at the i-th row from the top and the j-th column from the left is painted black, the j-th character in the string S_i is #; if that square is painted white, the j-th character in the string S_i is ..

Find the number of pairs of a black square c_1 and a white square c_2 that satisfy the following condition:

There is a path from the square c_1 to the square c_2 where we repeatedly move to a vertically or horizontally adjacent square through an alternating sequence of black and white squares: black, white, black, white...

Constraints

1 \leq H, W \leq 400

|S_i| = W (1 \leq i \leq H)

For each i (1 \leq i \leq H), the string S_i consists of characters # and ..

Input

Input is given from Standard Input in the following format:

H W
S_1
S_2
:
S_H

Output

Print the answer.

Sample Input 1

3 3
.#.
..#
#..

Sample Output 1

10

Some of the pairs satisfying the condition are ((1, 2), (3, 3)) and ((3, 1), (3, 2)), where (i, j) denotes the square at the i-th row from the top and the j-th column from the left.

Sample Input 2

2 4
....
....

Sample Output 2

0

Sample Input 3

4 3
###
###
...
###

Sample Output 3

6

Solution in C++14 (GCC 5.4.1) (judge verdict: Time Limit Exceeded)

#include <bits/stdc++.h>

#define mp make_pair

using namespace std;

typedef int32_t i32;
typedef uint32_t u32;
typedef int64_t i64;
typedef uint64_t u64;
typedef pair<int,int> pii;
typedef pair<i64,int> pli;
typedef pair<int,i64> pil;
typedef pair<i64,i64> pll;
typedef vector<int> vi;
typedef vector<i64> vl;

template <typename T>
T id(T b) {return b;};
template <class It>
bool all(It f,It l){return std::all_of(f,l,id<bool>);}
template <class It>
bool any(It f,It l){return std::any_of(f,l,id<bool>);}

const int MAX_H = 400, MAX_W = 400;
int h,w;
int s[MAX_H][MAX_W];
bool visited[MAX_H][MAX_W];
int dx[4] = {0,1,0,-1};
int dy[4] = {-1,0,1,0};

bool is_confined(int i, int j) {
  return 0 <= i && i < h && 0 <= j && j < w;
}

int dfs(int i, int j, int col) {
  //printf("%d %d %d\n",i,j,col);
  int res = col == 0 ? 1 : 0;

  if (s[i][j] != col) return 0;

  visited[i][j] = true;

  for (int k = 0; k < 4; k++) {
    int ni = i + dy[k], nj = j + dx[k];
    if (is_confined(ni,nj) && !visited[ni][nj])
      res += dfs(ni,nj,1-col);
  }

  return res;
}

void clear() {
  for (int i = 0; i < h; i++)
    for (int j = 0; j < w; j++)
      visited[i][j] = false;
}

int main()
{
  cin >> h >> w;
  for (int i = 0; i < h; i++) {
    string t;
    cin >> t;
    for (int j = 0; j < w; j++)
      s[i][j] = t[j] == '.' ? 0 : 1;
  }

  int res = 0;
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      clear();
      res += dfs(i,j,1);
    }
  }

  cout << res << endl;

  return 0;
}