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



Sample input:
3 3
.#.
..#
#..


Sample output:
10

Submission status: Runtime Error

Solution code:
(h, w)=list(map(lambda x: int(x), input().split()))
ms=[]
for y in range(0, h):
    for c in input():
        if c == '#':
            ms.append(True)
        else:
            ms.append(False)

edge=[]
for i in range(0, h * w):
    edge.append([])

for y in range(0, h):
    for x in range(0, w):
        if ms[w * y + x]:
            if x != 0:
                if not ms[w * y + x - 1]:
                    edge[w * y + x].append(w * y + x - 1)
            if x != w - 1:
                if not ms[w * y + x + 1]:
                    edge[w * y + x].append(w * y + x + 1)
            if y != 0:
                if not ms[(y - 1) * w + x]:
                    edge[w * y + x].append((y - 1) * w + x)
            if y != h - 1:
                if not ms[(y + 1) * w + x]:
                    edge[w * y + x].append((y + 1) * w + x)
        else:
            if x != 0:
                if ms[w * y + x - 1]:
                    edge[w * y + x].append(w * y + x - 1)
            if x != w - 1:
                if ms[w * y + x + 1]:
                    edge[w * y + x].append(w * y + x + 1)
            if y != 0:
                if ms[(y - 1) * w + x]:
                    edge[w * y + x].append((y - 1) * w + x)
            if y != h - 1:
                if ms[(y + 1) * w + x]:
                    edge[w * y + x].append((y + 1) * w + x)

def count_white(start, used):
    count=0
    for etow in edge[start]:
        # already traversed
        if etow in used:
            continue

        used.add(etow)
        count += 1

        for etob in edge[etow]:
            if etob in used:
                continue
            count += count_white(etob, used)
    return count

count=0
for i in range(0, h * w):
    if not ms[i]:
        continue
    
    count += count_white(i, set({i}))
print(count)

Submission status: Runtime Error

Solution code:
(h, w)=list(map(lambda x: int(x), input().split()))
ms=[]
for y in range(0, h):
    for c in input():
        if c == '#':
            ms.append(True)
        else:
            ms.append(False)

edge=[]
for i in range(0, h * w):
    edge.append([])

for y in range(0, h):
    for x in range(0, w):
        if ms[w * y + x]:
            if x != 0:
                if not ms[w * y + x - 1]:
                    edge[w * y + x].append(w * y + x - 1)
            if x != w - 1:
                if not ms[w * y + x + 1]:
                    edge[w * y + x].append(w * y + x + 1)
            if y != 0:
                if not ms[(y - 1) * w + x]:
                    edge[w * y + x].append((y - 1) * w + x)
            if y != h - 1:
                if not ms[(y + 1) * w + x]:
                    edge[w * y + x].append((y + 1) * w + x)
        else:
            if x != 0:
                if ms[w * y + x - 1]:
                    edge[w * y + x].append(w * y + x - 1)
            if x != w - 1:
                if ms[w * y + x + 1]:
                    edge[w * y + x].append(w * y + x + 1)
            if y != 0:
                if ms[(y - 1) * w + x]:
                    edge[w * y + x].append((y - 1) * w + x)
            if y != h - 1:
                if ms[(y + 1) * w + x]:
                    edge[w * y + x].append((y + 1) * w + x)

def count_white(start, used):
    count=0
    for etow in edge[start]:
        # already traversed
        if etow in used:
            continue

        used.add(etow)
        count += 1

        for etob in edge[etow]:
            if etob in used:
                continue
            count += count_white(etob, used)
    return count

count=0
for i in range(0, h * w):
    if not ms[i]:
        continue
    
    count += count_white(i, set({i}))

Submission status: Runtime Error

Solution code:
#!/mnt/c/Users/moiki/bash/env/bin/python
H,W      = list(map(int, input().split()))
S        =  [ list(input()) for _ in range(H)]

import sys
sys.setrecursionlimit(26000)

united_count = [ ]
# [ (黒1個、白2個) ,... k 個] 

directions = [(1,0), (0,1), (-1,0), (0,-1)] # y,x の順番


def dfs(pos, c, now_k):
    # pos : (1,2)
    # 引数は現在の連結成分の番号
    # 座標と、現在の1,0 が渡される
    # 渡されたnow_kで塗りつぶす
    y,x = pos
    for d in directions:
        try:
            if y+d[0] < 0 or x+d[1] < 0:
                continue
            content = S[y+d[0]][x+d[1]] 

            if c != content and (content == "#" or content == ".") :
                S[y+d[0]][x+d[1]] = now_k
                inplace_tuple     = united_count[now_k]
                united_count[now_k]     = ( inplace_tuple[0] + 1, inplace_tuple[1]) if content == "#" else \
                                    ( inplace_tuple[0]    , inplace_tuple[1]+1) # タプルなので新しく作る

                dfs( (y+d[0], x+d[1]),  content,  now_k)  # DFSかける

            else:
                continue
        except:
            continue



now_k = 0
for y in range(H):
    for x in range(W):
        c = S[y][x]  
        if c == "#" or c == "." :
            united_count.append( (1,0) if  c == "#" else (0,1) ) # now_k番目
            S[y][x] = now_k  # cの値は黒だったら、1 を入れてdfsに投げる

            pos = (y,x)
            dfs(pos, c, now_k)
            now_k         += 1

        else:
            continue # もう数字が入っている場合は、パス

# for y in range(H):
#     for x in range(W):
#         print(S[y][x], end="")
#     print("")


answer = 0
mod    = int(1e9)+7
for uni in united_count:
    answer = ((uni[0]*uni[1])%mod + answer) % mod

print(answer)

Submission status: Runtime Error

Solution code:
#!/mnt/c/Users/moiki/bash/env/bin/python
H,W      = list(map(int, input().split()))
S        =  [ list(input()) for _ in range(H)]

import sys
sys.setrecursionlimit(16000)

united_count = [ ]
# [ (黒1個、白2個) ,... k 個] 

directions = [(1,0), (0,1), (-1,0), (0,-1)] # y,x の順番


def dfs(pos, c, now_k):
    # pos : (1,2)
    # 引数は現在の連結成分の番号
    # 座標と、現在の1,0 が渡される
    # 渡されたnow_kで塗りつぶす
    y,x = pos
    for d in directions:
        try:
            if y+d[0] < 0 or x+d[1] < 0:
                continue
            content = S[y+d[0]][x+d[1]] 

            if c != content and (content == "#" or content == ".") :
                S[y+d[0]][x+d[1]] = now_k
                inplace_tuple     = united_count[now_k]
                united_count[now_k]     = ( inplace_tuple[0] + 1, inplace_tuple[1]) if content == "#" else \
                                    ( inplace_tuple[0]    , inplace_tuple[1]+1) # タプルなので新しく作る

                dfs( (y+d[0], x+d[1]),  content,  now_k)  # DFSかける

            else:
                continue
        except:
            continue



now_k = 0
for y in range(H):
    for x in range(W):
        c = S[y][x]  
        if c == "#" or c == "." :
            united_count.append( (1,0) if  c == "#" else (0,1) ) # now_k番目
            S[y][x] = now_k  # cの値は黒だったら、1 を入れてdfsに投げる

            pos = (y,x)
            dfs(pos, c, now_k)
            now_k         += 1

        else:
            continue # もう数字が入っている場合は、パス

# for y in range(H):
#     for x in range(W):
#         print(S[y][x], end="")
#     print("")


answer = 0
mod    = int(1e9)+7
for uni in united_count:
    answer = ((uni[0]*uni[1])%mod + answer) % mod

print(answer)

Submission status: Runtime Error

Solution code:
#!/mnt/c/Users/moiki/bash/env/bin/python
H,W      = list(map(int, input().split()))
S        =  [ list(input()) for _ in range(H)]


united_count = [ ]
# [ (黒1個、白2個) ,... k 個] 

directions = [(1,0), (0,1), (-1,0), (0,-1)] # y,x の順番


def dfs(pos, c, now_k):
    # pos : (1,2)
    # 引数は現在の連結成分の番号
    # 座標と、現在の1,0 が渡される
    # 渡されたnow_kで塗りつぶす
    y,x = pos
    for d in directions:
        try:
            if y+d[0] < 0 or x+d[1] < 0:
                continue
            content = S[y+d[0]][x+d[1]] 

            if c != content and (content == "#" or content == ".") :
                S[y+d[0]][x+d[1]] = now_k
                inplace_tuple     = united_count[now_k]
                united_count[now_k]     = ( inplace_tuple[0] + 1, inplace_tuple[1]) if content == "#" else \
                                    ( inplace_tuple[0]    , inplace_tuple[1]+1) # タプルなので新しく作る

                dfs( (y+d[0], x+d[1]),  content,  now_k)  # DFSかける

            else:
                continue
        except:
            continue



now_k = 0
for y in range(H):
    for x in range(W):
        c = S[y][x]  
        if c == "#" or c == "." :
            united_count.append( (1,0) if  c == "#" else (0,1) ) # now_k番目
            S[y][x] = now_k  # cの値は黒だったら、1 を入れてdfsに投げる

            pos = (y,x)
            dfs(pos, c, now_k)
            now_k         += 1

        else:
            continue # もう数字が入っている場合は、パス

# for y in range(H):
#     for x in range(W):
#         print(S[y][x], end="")
#     print("")


answer = 0
mod    = int(1e9)+7
for uni in united_count:
    answer = ((uni[0]*uni[1])%mod + answer) % mod

print(answer)

Submission status: Runtime Error

Solution code:
#!/mnt/c/Users/moiki/bash/env/bin/python
H,W      = list(map(int, input().split()))
S        =  [ list(input()) for _ in range(H)]


united_count = [ ]
# [ (黒1個、白2個) ,... k 個] 

directions = [(1,0), (0,1), (-1,0), (0,-1)] # y,x の順番


def dfs(pos, c, now_k):
    # pos : (1,2)
    # 引数は現在の連結成分の番号
    # 座標と、現在の1,0 が渡される
    # 渡されたnow_kで塗りつぶす
    y,x = pos
    for d in directions:
        try:
            if y+d[0] < 0 or x+d[1] < 0:
                continue
            content = S[y+d[0]][x+d[1]] 

            if c != content and (content == "#" or content == ".") :
                S[y+d[0]][x+d[1]] = now_k
                inplace_tuple     = united_count[now_k]
                united_count[now_k]     = ( inplace_tuple[0] + 1, inplace_tuple[1]) if content == "#" else \
                                    ( inplace_tuple[0]    , inplace_tuple[1]+1) # タプルなので新しく作る

                dfs( (y+d[0], x+d[1]),  content,  now_k)  # DFSかける

            else:
                continue
        except IndexError:
            continue



now_k = 0
for y in range(H):
    for x in range(W):
        c = S[y][x]  
        if c == "#" or c == "." :
            united_count.append( (1,0) if  c == "#" else (0,1) ) # now_k番目
            S[y][x] = now_k  # cの値は黒だったら、1 を入れてdfsに投げる

            pos = (y,x)
            dfs(pos, c, now_k)
            now_k         += 1

        else:
            continue # もう数字が入っている場合は、パス

# for y in range(H):
#     for x in range(W):
#         print(S[y][x], end="")
#     print("")


answer = 0
mod    = int(1e9)+7
for uni in united_count:
    answer = ((uni[0]*uni[1])%mod + answer) % mod

print(answer)

Submission status: Runtime Error

Solution code:
#!/mnt/c/Users/moiki/bash/env/bin/python
H,W      = list(map(int, input().split()))
S        =  [ list(input()) for _ in range(H)]
NUM_GRID = [ [-1] * W for _ in range(H) ]


united_count = [ ]
# [ (黒1個、白2個) ,... k 個] 

directions = [(1,0), (0,1), (-1,0), (0,-1)] # y,x の順番
def dfs(pos, c, now_k):
    # pos : (1,2)
    # 引数は現在の連結成分の番号
    # 座標と、現在の1,0 が渡される
    # 渡されたnow_kで塗りつぶす
    y,x = pos
    for d in directions:
        if y+d[0] < 0 or x+d[1] < 0 or y+d[0] >= H or x+d[1] >= W:
            continue

        content = S[y+d[0]][x+d[1]] 

        if c != content and NUM_GRID[y+d[0]][x+d[1]] == -1:

            NUM_GRID[y+d[0]] [x+d[1]] = now_k  # 塗る
            inplace_tuple     = united_count[now_k]
            united_count[now_k]     = ( inplace_tuple[0] + 1, inplace_tuple[1]) if content == "#" else \
                                ( inplace_tuple[0]    , inplace_tuple[1]+1) # タプルなので新しく作る

            dfs( (y+d[0], x+d[1]),  content,  now_k)  # DFSかける

        else:
            continue



now_k = 0
for y in range(H):
    for x in range(W):
        c = S[y][x]  
        if NUM_GRID[y][x] == -1:

            united_count.append( (1,0) if  c == "#" else (0,1) ) # now_k番目
            NUM_GRID[y][x] = now_k  # cの値は黒だったら、1 を入れてdfsに投げる

            pos = (y,x)
            dfs(pos, c, now_k)
            now_k         += 1

        else:
            continue # もう数字が入っている場合は、パス

# for y in range(H):
#     for x in range(W):
#         print(NUM_GRID[y][x], end="")
#     print("")


answer = 0
mod    = int(1e9)+7
for uni in united_count:
    answer = ((uni[0]*uni[1])%mod + answer) % mod

print(answer)

Submission status: Runtime Error

Solution code:
#!/mnt/c/Users/moiki/bash/env/bin/python
H,W      = list(map(int, input().split()))
S        =  [ list(input()) for _ in range(H)]
NUM_GRID = [ [-1] * W for _ in range(H) ]


united_count = [ ]
# [ (黒1個、白2個) ,... k 個] 

directions = [(1,0), (0,1), (-1,0), (0,-1)] # y,x の順番
def dfs(pos, c, now_k):
    # pos : (1,2)
    # 引数は現在の連結成分の番号
    # 座標と、現在の1,0 が渡される
    # 渡されたnow_kで塗りつぶす
    y,x = pos
    for d in directions:
        if y+d[0] < 0 or x+d[1] < 0:
            continue
        try:
            content = S[y+d[0]][x+d[1]] 

            if c != content and NUM_GRID[y+d[0]][x+d[1]] == -1:

                NUM_GRID[y+d[0]] [x+d[1]] = now_k  # 塗る
                inplace_tuple     = united_count[now_k]
                united_count[now_k]     = ( inplace_tuple[0] + 1, inplace_tuple[1]) if content == "#" else \
                                    ( inplace_tuple[0]    , inplace_tuple[1]+1) # タプルなので新しく作る

                dfs( (y+d[0], x+d[1]),  content,  now_k)  # DFSかける
            else:
                continue

        except IndexError: # はじっこに来た
            continue


now_k = 0
for y in range(H):
    for x in range(W):
        c = S[y][x]  
        if NUM_GRID[y][x] == -1:

            united_count.append( (1,0) if  c == "#" else (0,1) ) # now_k番目
            NUM_GRID[y][x] = now_k  # cの値は黒だったら、1 を入れてdfsに投げる

            pos = (y,x)
            dfs(pos, c, now_k)
            now_k         += 1

        else:
            continue # もう数字が入っている場合は、パス

# for y in range(H):
#     for x in range(W):
#         print(NUM_GRID[y][x], end="")
#     print("")


answer = 0
mod    = int(1e9)+7
for uni in united_count:
    answer = ((uni[0]*uni[1])%mod + answer) % mod

print(answer)

Submission status: Runtime Error

Solution code:
h,w = map(int, input().split())
s = []
for i in range(h):
    s.append(input())
dx = [0,0,1,-1]
dy = [1,-1,0,0]
def dfs(y,x):
    global check
    global was
    was[y][x] = 1
    if s[y][x] == "#":
        check[0] += 1
    else:
        check[1] += 1
    for k in range(4):
        nx = x + dx[k]
        ny = y + dy[k]
        if ny >= 0 and nx >= 0 and nx < w and ny < h and s[ny][nx] != s[y][x] and not was[ny][nx]:
            dfs(ny,nx)
ans = 0
was = [[0 for i in range(w)] for j in range(h)]
for i in range(h):
    for j in range(w):
        if not was[i][j]:
            check = [0,0]
            dfs(i,j)
            ans += check[0] * check[1]
print(ans)

Submission status: Runtime Error

Solution code:
h,w = map(int, input().split())
s = []
for i in range(h):
    s.append(input())
dx = [0,0,1,-1]
dy = [1,-1,0,0]
def dfs(y,x):
    global check
    global was
    was[y][x] = 1
    if s[y][x] == "#":
        check[0] += 1
    else:
        check[1] += 1
    for k in range(4):
        nx = x + dx[k]
        ny = y + dy[k]
        if ny >= 0 and ny >= 0 and nx < w and ny < h and s[ny][nx] != s[y][x] and not was[ny][nx]:
            dfs(ny,nx)
ans = 0
was = [[0 for i in range(w)] for j in range(h)]
for i in range(h):
    for j in range(w):
        if not was[i][j]:
            check = [0,0]
            dfs(i,j)
            ans += check[0] * check[1]
print(ans)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(200000)
h,w = map(int, input().split())
s = [input() for _ in range(h)]
dx = [0,0,1,-1]
dy = [1,-1,0,0]
def dfs(x,y):
    global check
    global was
    was[y][x] = 1
    if s[y][x] == "#":
        check[0] += 1
    else:
        check[1] += 1
    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]
        if ny >= 0 and ny >= 0 and nx < w and ny < h and s[ny][nx] != s[y][x] and not was[ny][nx]:
            dfs(nx,ny)
ans = 0
was = [[0 for i in range(h)] for j in range(w)]
for i in range(h):
    for j in range(w):
        if not was[i][j]:
            check = [0,0]
            dfs(i,j)
            ans += check[0] * check[1]
print(ans)

Submission status: Runtime Error

Solution code:
import itertools
H, W = [int(_) for _ in input().split()]
S = [input() for _ in range(H)]
A = [[0 for _ in range(W)] for _ in range(H)]
count = {}


def dfs(x, y, p, q):
    if A[x][y] == 1:
        return
    else:
        A[x][y] = 1
        count[p * H + q] = count.get(p * H + q, {})
        count[p * H + q][S[x][y]] = count[p * H + q].get(S[x][y], 0) + 1
        dxy = [[-1, 0], [1, 0], [0, -1], [0, 1]]
        for dx, dy in dxy:
            nx, ny = x + dx, y + dy
            if 0 <= nx < H and 0 <= ny < W:
                if S[x][y] == S[nx][ny]:
                    dfs(nx, ny, nx, ny)
                else:
                    dfs(nx, ny, p, q)


dfs(0, 0, 0, 0)
ans = 0
for i in count:
    ans += count[i].get('#', 0) * count[i].get('.', 0)
print(ans)

Submission status: Runtime Error

Solution code:
def main():
    """
    1 <= H, W <= 400
    |Si| = W  (#, .)
    """
    H, W = map(int, input().split())
    S = [input() for _ in range(H)]

    ans = f(H, W, S)
    print(ans)


def f(H, W, S):
    ans1 = editorial(H, W, S)
    ans2 = f_rec(H, W, S)

    assert ans1 == ans2
    return ans1


def editorial(H, W, S):
    """
    ある地点からの黒と白のマスの数
    黒から白への行き方は
    黒の数から白の数
    """
    from collections import deque
    di = [1, 0, -1, 0]
    dj = [0, 1, 0, -1]
    color = [[S[i][j] == "#" for j in range(W)]
             for i in range(H)]
    used = [[False] * W for i in range(H)]

    ans = 0
    for i in range(H):
        for j in range(W):
            if used[i][j]:
                continue
            used[i][j] = True

            b, w = 0, 0
            que = deque([(i, j)])
            while que:
                ci, cj = que.pop()
                if color[ci][cj]:
                    b += 1
                else:
                    w += 1

                for d in range(4):
                    ni = ci + di[d]
                    nj = cj + dj[d]
                    in_range = 0 <= ni < H and 0 <= nj < W
                    if not in_range:
                        continue
                    if used[ni][nj]:
                        continue
                    if color[ci][cj] == color[ni][nj]:
                        continue

                    used[ni][nj] = True
                    que.append((ni, nj))

            ans += b * w

    return ans


def f_rec(H, W, S):
    dx = [0, 0, 1, -1]
    dy = [1, -1, 0, 0]

    def rec(h, w, vis):
        vis[h][w] = True
        bl, wh = 0, 0
        if S[h][w] == "#":
            bl += 1
        else:
            wh += 1

        for i in range(4):
            ny = h + dy[i]
            nx = w + dx[i]
            in_range = 0 <= ny < H and 0 <= nx < W
            if in_range and not vis[ny][nx] and S[ny][nx] != S[h][w]:
                n_bl, n_wh = rec(ny, nx, vis)
                bl += n_bl
                wh += n_wh

        return bl, wh

    vis = [[False] * W for _ in range(H)]
    ans = 0
    for h in range(H):
        for w in range(W):
            bl, wh = rec(h, w, vis)
            ans += bl * wh

    return ans


def TLE_pypy3(H, W, S):
    """
    c1 to c2:
        c1: black(#), c2: white(.)
        c1 - not c1 - c1 - c2

    上下左右に隣り合うマスへの移動を繰り返し
    a to b: N * N = 400 ^ 2 = 1.6 * 10^5
    Nb to Nw == Nw to Nb

    あるマスからどこまで進めるか（直線）
    North <-> South
    West  <-> East

    a to b: ok
    b to c: ok
    a to c: ok (3段論法)

    """
    # south, north, east, west
    d = zip([0, 0, 1, -1],
            [1, -1, 0, 0])
    d = list(d)
    to = {"#": ".", ".": "#"}

    b = []
    for _ in range(H):
        b2 = []
        for _ in range(W):
            b2.append([None] * 4)
        b.append(b2)

    blacks = {}
    for y in range(H):
        for x in range(W):
            src = S[y][x]
            if src == "#":
                blacks[(y, x)] = -1

            for i, (dx, dy) in enumerate(d):
                nx = x + dx
                ny = y + dy

                valid = 0 <= nx < W and 0 <= ny < H
                if not valid:
                    continue

                if S[ny][nx] == to[src]:
                    b[y][x][i] = (ny, nx)

    ans = 0
    # #からなので、候補
    for (y, x), _ in blacks.items():
        # 黒から辿り、１ターンでー候補白を見つけ黒へたどる、次のターンの黒を見つける
        bs = [(y, x)]
        # 辿った黒白のマスをまた辿らないようにする
        used_bs = {}
        used_ws = {}
        while bs:
            by, bx = bs.pop()
            used_bs[(by, bx)] = None

            # 黒から白
            whites = []
            for pos in b[by][bx]:
                if pos and pos not in used_ws:
                    ans += 1
                    whites.append(pos)
                    used_ws[pos] = None

            # 白から黒
            for wy, wx in whites:
                for pos in b[wy][wx]:
                    if pos and pos not in used_bs:
                        bs.append(pos)

    return ans


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
H, W = [int(x) for x in input().strip().split(" ")]

import sys
sys.setrecursionlimit(100000)
b = []
bset = set()
wset = set()
i = 0
j = 0
for line in sys.stdin:
    b.append(line.strip())
    for s in line.strip():
        if s == "#":
            bset.add((i, j))
        else:
            wset.add((i, j))
        j += 1
    j = 0
    i += 1

fbset = set()
fwset = set()

def it_b(i, j):
    fbset.add((i, j))
    totalb = 1
    totalw = 0
    bset.remove((i, j))
    #print("b", i,j)
    if i - 1 >= 0:
        if b[i-1][j] == "." and (i-1, j) not in fwset:
            rb, rw = it_w(i-1, j)
            totalb += rb
            totalw += rw
    if j - 1 >= 0:
        if b[i][j-1] == "." and (i, j-1) not in fwset:
            rb, rw = it_w(i, j-1)
            totalb += rb
            totalw += rw
    if i + 1 <= H-1:
        if b[i+1][j] == "." and (i+1, j) not in fwset:
            rb, rw = it_w(i+1, j)
            totalb += rb
            totalw += rw
    if j + 1 <= W-1:
        if b[i][j+1] == "." and (i, j+1) not in fwset:
            rb, rw = it_w(i, j+1)
            totalb += rb
            totalw += rw
    return totalb, totalw

def it_w(i, j):
    fwset.add((i, j))
    totalb = 0
    totalw = 1
    #print("w", i,j)
    if i - 1 >= 0:
        if b[i-1][j] == "#" and (i-1, j) not in fbset:
            rb, rw = it_b(i-1, j)
            totalb += rb
            totalw += rw
    if j - 1 >= 0:
        if b[i][j-1] == "#" and (i, j-1) not in fbset:
            rb, rw = it_b(i, j-1)
            totalb += rb
            totalw += rw
    if i + 1 <= H-1:
        if b[i+1][j] == "#" and (i+1, j) not in fbset:
            rb, rw = it_b(i+1, j)
            totalb += rb
            totalw += rw
    if j + 1 <= W-1:
        if b[i][j+1] == "#" and (i, j+1) not in fbset:
            rb, rw = it_b(i, j+1)
            totalb += rb
            totalw += rw
    return totalb, totalw

t = 0
while True:
    if len(bset) == 0:
        break
    x = bset.pop()
    bset.add(x)
    rb, rw = it_b(x[0], x[1])
    t += rb * rw
print(t)

Submission status: Runtime Error

Solution code:
H, W = [int(x) for x in input().strip().split(" ")]

import sys
b = []
bset = set()
wset = set()
i = 0
j = 0
for line in sys.stdin:
    b.append(line.strip())
    for s in line.strip():
        if s == "#":
            bset.add((i, j))
        else:
            wset.add((i, j))
        j += 1
    j = 0
    i += 1

fbset = set()
fwset = set()

def it_b(i, j):
    fbset.add((i, j))
    totalb = 1
    totalw = 0
    bset.remove((i, j))
    #print("b", i,j)
    if i - 1 >= 0:
        if b[i-1][j] == "." and (i-1, j) not in fwset:
            rb, rw = it_w(i-1, j)
            totalb += rb
            totalw += rw
    if j - 1 >= 0:
        if b[i][j-1] == "." and (i, j-1) not in fwset:
            rb, rw = it_w(i, j-1)
            totalb += rb
            totalw += rw
    if i + 1 <= H-1:
        if b[i+1][j] == "." and (i+1, j) not in fwset:
            rb, rw = it_w(i+1, j)
            totalb += rb
            totalw += rw
    if j + 1 <= W-1:
        if b[i][j+1] == "." and (i, j+1) not in fwset:
            rb, rw = it_w(i, j+1)
            totalb += rb
            totalw += rw
    return totalb, totalw

def it_w(i, j):
    fwset.add((i, j))
    totalb = 0
    totalw = 1
    #print("w", i,j)
    if i - 1 >= 0:
        if b[i-1][j] == "#" and (i-1, j) not in fbset:
            rb, rw = it_b(i-1, j)
            totalb += rb
            totalw += rw
    if j - 1 >= 0:
        if b[i][j-1] == "#" and (i, j-1) not in fbset:
            rb, rw = it_b(i, j-1)
            totalb += rb
            totalw += rw
    if i + 1 <= H-1:
        if b[i+1][j] == "#" and (i+1, j) not in fbset:
            rb, rw = it_b(i+1, j)
            totalb += rb
            totalw += rw
    if j + 1 <= W-1:
        if b[i][j+1] == "#" and (i, j+1) not in fbset:
            rb, rw = it_b(i, j+1)
            totalb += rb
            totalw += rw
    return totalb, totalw

t = 0
while True:
    if len(bset) == 0:
        break
    x = bset.pop()
    bset.add(x)
    rb, rw = it_b(x[0], x[1])
    t += rb * rw
print(t)

Submission status: Runtime Error

Solution code:
#encoding:utf-8

import numpy as np
import sys
sys.setrecursionlimit(1000000)

H, W = map(int, input().split())
S = []
for i in range(H):
    s = list(input())
    S.append(s)



def count_answer(x,y,num_b,num_w):
    # print(used)

    if S[x][y] == "#":
        num_b += 1
    else:
        num_w += 1
    used[x][y] = 1
    dx = [0,0,1,-1]
    dy = [1,-1,0,0]
    # print("x,y:",x,y)
    for i in range(4):
        next_x = x + dx[i]
        next_y = y + dy[i]
        # print(next_x,next_y)
        if next_x == -1 or next_y == -1 or next_x >= H or next_y >= W:
            pass
        elif used[next_x,next_y] == 1:
            pass
        elif S[next_x][next_y] != S[x][y]:
            num_b,num_w = count_answer(next_x,next_y,num_b,num_w)
    return num_b,num_w

answer = 0
used = np.zeros((H,W))
for i in range(H):
    for j in range(W):
        if used[i][j] == 1:
            continue
        num_b = 0
        num_w = 0
        if S[i,j] == "#":
            num_b,num_w  = count_answer(i,j,num_b,num_w)
            answer += num_b*num_w
print(answer)

Submission status: Runtime Error

Solution code:
#encoding:utf-8

import numpy as np
# import sys
# sys.setrecursionlimit(1000000)

H, W = map(int, input().split())
S = []
for i in range(H):
    s = list(input())
    S.append(s)

S_ = np.array(S)

def count_answer(x,y,num_b,num_w):
    # print(used)
    # global num_b,num_w
    if S_[x][y] == "#":
        num_b += 1
    else:
        num_w += 1
    used[x][y] = 1
    dx = [0,0,1,-1]
    dy = [1,-1,0,0]
    # print("x,y:",x,y)
    for i in range(4):
        next_x = x + dx[i]
        next_y = y + dy[i]
        # print(next_x,next_y)
        if next_x == -1 or next_y == -1 or next_x >= H or next_y >= W:
            pass
        elif used[next_x,next_y] == 1:
            pass
        elif S_[next_x][next_y] != S_[x][y]:
            num_b,num_w = count_answer(next_x,next_y,num_b,num_w)
    return num_b,num_w

answer = 0
used = np.zeros((H,W))
for i in range(H):
    for j in range(W):
        if used[i][j] == 1:
            continue
        num_b = 0
        num_w = 0
        if S_[i,j] == "#":
            num_b,num_w  = count_answer(i,j,num_b,num_w)
            answer += num_b*num_w
print(answer)

Submission status: Runtime Error

Solution code:
#encoding:utf-8

import numpy as np
# import sys
# sys.setrecursionlimit(1000000)

H, W = map(int, input().split())
S = []
for i in range(H):
    s = list(input())
    S.append(s)

S_ = np.array(S)

def count_answer(x,y,num_b,num_w):
    # print(used)
    # global num_b,num_w
    if S_[x][y] == "#":
        num_b += 1
    else:
        num_w += 1
    used[x][y] = 1
    dx = [0,0,1,-1]
    dy = [1,-1,0,0]
    # print("x,y:",x,y)
    for i in range(4):
        next_x = x + dx[i]
        next_y = y + dy[i]
        # print(next_x,next_y)
        if next_x == -1 or next_y == -1 or next_x >= H or next_y >= W or used[next_x,next_y] == 1:
            pass

        elif S_[next_x][next_y] != S_[x][y]:
            num_b,num_w = count_answer(next_x,next_y,num_b,num_w)
    return num_b,num_w

answer = 0
used = np.zeros((H,W))
for i in range(H):
    for j in range(W):
        if used[i][j] == 1:
            continue
        num_b = 0
        num_w = 0
        num_b,num_w  = count_answer(i,j,num_b,num_w)
        answer += num_b*num_w
print(answer)

Submission status: Runtime Error

Solution code:
#encoding:utf-8

import numpy as np
# import sys
# sys.setrecursionlimit(1000000)

H, W = map(int, input().split())
S = []
for i in range(H):
    s = list(input())
    S.append(s)

S_ = np.array(S)

def count_answer(x,y,num_b,num_w):
    # print(used)
    # global num_b,num_w
    if S_[x][y] == "#":
        num_b += 1
    else:
        num_w += 1
    used[x][y] = 1
    dx = [0,0,1,-1]
    dy = [1,-1,0,0]
    # print("x,y:",x,y)
    for i in range(4):
        next_x = x + dx[i]
        next_y = y + dy[i]
        # print(next_x,next_y)
        if next_x == -1 or next_y == -1 or next_x >= H or next_y >= W or used[next_x,next_y] == 1:
            continue
        if S_[next_x][next_y] != S_[x][y]:
            num_b,num_w = count_answer(next_x,next_y,num_b,num_w)
    return num_b,num_w

answer = 0
used = np.zeros((H,W))
for i in range(H):
    for j in range(W):
        if used[i][j] == 1:
            continue
        num_b = 0
        num_w = 0
        num_b,num_w  = count_answer(i,j,num_b,num_w)
        answer += num_b*num_w
print(answer)