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 Ruby (2.3.3) (judge verdict: Runtime Error)

#include<bits/stdc++.h>
using namespace std;

typedef struct{int x,y;}zahyo;

char s[410][410];
int h,w,dx[4]={1,0,-1,0},dy[4]={0,-1,0,1};
vector<zahyo>past;

int sum(zahyo c){
    int ret=0;
    for(int i=0;i<4;i++){
        zahyo n;
        n.x=c.x+dx[i],n.y=c.y+dy[i];
        bool flg=false;
        for(zahyo r:past)if(n.x==r.x&&n.y==r.y)flg=true;
        if((0>n.x||n.x>=w||0>n.y||n.y>=h)||flg)continue;
        past.push_back(n);
        if(s[c.y][c.x]=='#'&&s[n.y][n.x]=='.')ret+=1+sum(n);
        if(s[c.y][c.x]=='.'&&s[n.y][n.x]=='#')ret+=sum(n);
    }
    return ret;
}

int main(){
    scanf("%d%d",&h,&w);
    for(int i=0;i<h;i++)scanf("%s",s[i]);

    int x,y,ans=0;
    for(x=0;x<w;x++)for(y=0;y<h;y++)if(s[y][x]=='#'){ //全部の＃に対して
        past.clear();
        zahyo start;
        start.x=x; start.y=y;
        ans+=sum(start);
    }
    printf("%d\n",ans);
}