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 Rust (1.15.1) (judge verdict: Accepted)

#[allow(unused_imports)]
use std::cmp::{Ordering};

#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};

#[allow(unused_imports)]
use std::io::{stdin, stdout, BufWriter, Write};

#[allow(unused_imports)]
use std::iter::FromIterator;

#[allow(unused_macros)]
macro_rules! min {
    ($x: expr) => ($x);
    ($x: expr, $($z: expr),+) => {{
        std::cmp::min($x, min!($($z),*))
    }}
}

#[allow(unused_macros)]
macro_rules! max {
    ($x: expr) => ($x);
    ($x: expr, $($z: expr),+) => {{
        std::cmp::max($x, max!($($z),*))
    }}
}

#[allow(unused_macros)]
macro_rules! get { 
    ([$t: ty]) => { 
        { 
            let mut line = String::new(); 
            stdin().read_line(&mut line).unwrap(); 
            line.split_whitespace().map(|t|t.parse::<$t>().unwrap()).collect::<Vec<_>>()
        }
    };
    ([$t: ty];$n: expr) => {
        (0..$n).map(|_|get!([$t])).collect::<Vec<_>>()
    };
    ($t: ty) => {
        {
            let mut line = String::new();
            stdin().read_line(&mut line).unwrap();
            line.trim().parse::<$t>().unwrap()
        }
    };
    ($($t: ty),*) => {
        { 
            let mut line = String::new();
            stdin().read_line(&mut line).unwrap();
            let mut iter = line.split_whitespace();
            ($(iter.next().unwrap().parse::<$t>().unwrap(),)*)
        }
    };
    ($t: ty; $n: expr) => {
        (0..$n).map(|_|get!($t)).collect::<Vec<_>>()
    };
    ($($t: ty),*; $n: expr) => {
        (0..$n).map(|_|get!($($t),*)).collect::<Vec<_>>()
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        #[cfg(debug_assertions)]
        writeln!(&mut std::io::stderr(), concat!("[DEBUG] ", $(stringify!($a), "={:?} "),*), $($a),*).unwrap();
    }
}

const BIG_STACK_SIZE: bool = true;

#[allow(dead_code)]
fn main() {
    use std::thread;
    if BIG_STACK_SIZE {
        thread::Builder::new()
            .stack_size(32 * 1024 * 1024)
            .name("solve".into())
            .spawn(solve)
            .unwrap()
            .join()
            .unwrap();
    } else {
        solve();
    }
}

struct Graph<T> {
    edge: BTreeMap<T, BTreeSet<T>>,
}

impl<T: Ord + Copy + Clone + std::fmt::Debug> Graph<T> {
    fn new() -> Self {
        Graph{
            edge: BTreeMap::new(),
        }
    }

    fn add(&mut self, a: T, b: T) {
        self.edge.entry(a).or_insert(BTreeSet::new()).insert(b);
        self.edge.entry(b).or_insert(BTreeSet::new()).insert(a);
    }

    fn bfs(&self) -> usize {
        let mut searched = BTreeSet::<T>::new();
        let mut vec = Vec::new();
        for k in self.edge.keys() {
            if searched.contains(k) {
                continue;
            }
            searched.insert(*k);
            let mut b = 0;
            let mut w = 0;
            let mut queue = VecDeque::new();
            queue.push_back((k, 0));
            while let Some((key, depth)) = queue.pop_front() {
                let vs = self.edge.get(key).unwrap().iter().filter(|e| !searched.contains(*e)).collect::<Vec<_>>();
                for v in vs {
                    searched.insert(*v);
                    queue.push_back((v, depth+1));
                }
                if depth % 2 == 0 {
                    b += 1;
                } else {
                    w += 1;
                }
            }
            vec.push((b,w));
        }
        vec.into_iter().map(|(a,b)| a*b).sum()
    }
}

fn solve() {
    let (h, w) = get!(usize, usize);
    let s = get!(String; h).into_iter().map(|e| e.chars().map(|f| if f == '#' { true } else { false }).collect::<Vec<_>>()).collect::<Vec<_>>();
    let mut graph = Graph::new();
    for row in 0..h {
        for col in 0..w {
            let m = s[row][col];
            if row > 0 && s[row-1][col] != m {
                graph.add((row,col),(row-1, col));
            }
            if row < h-1 && s[row+1][col] != m {
                graph.add((row,col),(row+1, col));
            }
            if col > 0 && s[row][col-1] != m {
                graph.add((row,col), (row,col-1));
            }
            if col < w-1 && s[row][col+1] != m {
                graph.add((row, col), (row,col+1));
            }
        }
    }
    println!("{}", graph.bfs());
}