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++ (GCC 9.2.1) (judge verdict: Runtime Error)

#include <algorithm>
#include <bitset>
#include <cassert>
#include <cmath>
#include <climits>
#include <cstdlib>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <string>
#include <vector>
#define DEBUG 1
using namespace std;
constexpr int kMod = 1000000007;
typedef long long LL;
typedef pair<int, int> P;

int H, W;
vector<string> S;

int bfs(int sx, int sy) {
  vector<vector<bool>> visited(H, vector<bool>(W, false));
  visited[sx][sy] = true;
  deque<P> que; que.push_back({sx, sy});

  int cnt = 0;
  vector<P> ds = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};
  while (!que.empty()) {
    auto [x, y] = que.front(); que.pop_front();
    for (auto [dx, dy] : ds) {
      int nx = x + dx, ny = y + dy;
      if (nx < 0 || W <= nx || ny < 0 || H <= ny) continue;
      if (visited[ny][nx]) continue;
      if (S[y][x] == S[ny][nx]) continue;

      visited[ny][nx] = true;
      que.push_back({nx, ny});
      if (S[ny][nx] == '.') ++cnt;
    }
  }
  return cnt;
}

int main() {
  cin >> H >> W;
  S.resize(H);
  vector<P> black, white;
  for (int r = 0; r < H; ++r) {
    cin >> S[r];
    for (int c = 0; c < W; ++c) {
      if (S[r][c] == '#') black.push_back({r, c});
      else                white.push_back({r, c});
    }
  }

  int cnt = 0;
  for (auto [sy, sx] : black) {
    cnt += bfs(sx, sy);
  }

  cout << cnt << endl;
}