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:
# https://atcoder.jp/contests/aising2019/tasks/aising2019_c

H, W = map(int, input().split())
M = [list(input()) for _ in range(H)]
seen = [[False for _ in range(W)] for _ in range(H)]


def dfs(h, w, ph, pw):
    if M[h][w] == '.':
        bc, wc = 0, 1
    else:
        bc, wc = 1, 0
    for (dh, dw) in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
        nh, nw = h + dh, w + dw
        if nh < 0 or H <= nh or nw < 0 or W <= nw:
            continue
        if nh == ph and nw == pw:
            continue
        if seen[nh][nw]:
            continue
        if M[nh][nw] == M[h][w]:
            continue
        seen[nh][nw] = True
        b_add, w_add = dfs(nh, nw, h, w)
        bc += b_add
        wc += w_add
    return bc, wc

ans = 0
for h in range(H):
    for w in range(W):
        if seen[h][w] == False:
            seen[h][w] = True
            b, w = dfs(h, w, -1, -1)
            ans += b * w
print(ans)

Submission status: Runtime Error

Solution code:
# https://atcoder.jp/contests/aising2019/tasks/aising2019_c

H, W = map(int, input().split())
M = [list(input()) for _ in range(H)]
seen = [[False] * W for _ in range(H)]


def dfs(h, w, ph, pw, color):
    nc = "." if color == "#" else "#"
    bc, bw = 0, 0
    if color == '#':
        bc += 1
    if color == '.':
        bw += 1
    
    path = []
    for (dh, dw) in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
        nh, nw = h + dh, w + dw
        if nh < 0 or H <= nh or nw < 0 or W <= nw:
            continue
        if nh == ph and nw == pw:
            continue
        if seen[nh][nw]:
            continue
        if M[nh][nw] != nc:
            continue

        seen[nh][nw] = True
        b_add, w_add = dfs(nh, nw, h, w, nc)
        bc += b_add
        bw += w_add
    return bc, bw

ans = 0
for h in range(H):
    for w in range(W):
        if seen[h][w] == False:
            seen[h][w] = True
            (b, w) = dfs(h, w, -1, -1, M[h][w])
            ans += b * w
print(ans)

Submission status: Runtime Error

Solution code:
h, w = map(int, input().split())
s = [input() for _ in range(h)]
seen = [[False for _ in range(w)] for _ in range(h)]

def dfs(bx, by, sx, sy):
    if s[sx][sy] == '.':
        b_cnt, w_cnt = 0, 1
    else:
        b_cnt, w_cnt = 1, 0
    for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
        px, py = sx + dx, sy + dy
        #print('=', px, py)
        if bx == px and by == py:
            #print(px, py, 'flg1')
            continue
        if px < 0 or h <= px or py < 0 or w <= py:
            #print(px, py, 'flg2')
            continue
        if seen[px][py]:
            #print(px, py, 'flg3')
            continue
        if s[sx][sy] == s[px][py]:
            #print(px, py, 'flg4')
            continue
        seen[px][py] = True
        b_add, w_add = dfs(sx, sy, px, py)
        b_cnt += b_add
        w_cnt += w_add

    return b_cnt, w_cnt

ans = 0
#print(dfs(-1, -1, 1, 1))
for i in range(h):
    for j in range(w):
        if seen[i][j] == False:
            seen[i][j] = True
            b_cnt, w_cnt = dfs(-1, -1, i, j)
            ans += b_cnt * w_cnt

print(ans)

Submission status: Runtime Error

Solution code:
h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
dx = (0, 0, 1, -1)
dy = (1, -1, 0, 0)
seen = [[False] * w for _ in range(h)]

numb = 0
numw = 0


def dfs(x, y):
    global numb, numw
    seen[x][y] = True
    if s[x][y] == '#':
        numb += 1
    else:
        numw += 1
    for di in range(4):
        nx = x + dx[di]
        ny = y + dy[di]
        if (nx < 0 or nx >= h or ny < 0 or ny >= w):
            continue
        if s[x][y] == s[nx][ny]:
            continue
        if seen[nx][ny]:
            continue
        dfs(nx, ny)


ans = 0
for x in range(h):
    for y in range(w):
        if seen[x][y]:
            continue
        if s[x][y] == '.':
            continue
        numb = 0
        numw = 0
        dfs(x, y)
        ans += numb * numw
print(ans)

Submission status: Runtime Error

Solution code:
h,w = map(int,input().split())
F = []
for i in range(h):
  F.append(list(input()))
  
V = [[False]*w for _ in range(h)]

def dfs(y,x,c):      
  V[y][x] = True
  black = 0
  white = 0
  if c =='#':
    black+=1
  else:
    white+=1
  for dy,dx in [(-1,0),(0,1),(1,0),(0,-1)]:
    ny = y + dy
    nx = x + dx
    if 0<=ny<h and 0<=nx<w:      
      if F[ny][nx]!=c and V[ny][nx] == False:
        nc = '#'
        if c =='#':
          nc = '.'
        bn,wn = dfs(ny,nx,nc)
        black += bn
        white += wn  
  return black,white
        
ans = 0
for i in range(h):
  for j in range(w):
    if F[i][j] == '#':      
      black,white = dfs(i,j,'#')
      ans += black*white
      
print(ans)

Submission status: Runtime Error

Solution code:
H, W = map(int, input().split())
s_list = []
for _ in range(H):
    s = input()
    s_list.append(s)
ans = 0
visited = set({})
for h in range(H):
    for w in range(W):
        if s_list[h][w] == '.':
            if str(h) + '_' + str(w) not in visited:
                d = deque()
                d.append([h, w])
                plus = 1
                minus = 0
                while d:
                    i, j = d.pop()
                    visited.add(str(i) + '_' + str(j))
                    for ii, jj in [[1, 0], [-1, 0], [0, 1], [0, -1]]:
                        if (0 <= (i + ii) < H) & (0 <= (j + jj) < W):
                            if str(i + ii) + '_' + str(j + jj) not in visited:
                                if s_list[i][j] != s_list[i + ii][j + jj]:
                                    d.append([i + ii, j + jj])
                                    visited.add(str(i + ii) + '_' + str(j + jj))
                                    if s_list[i + ii][j + jj] == '.':
                                        plus += 1
                                    else:
                                        minus += 1                                
                ans += plus * minus
print(ans)

Submission status: Runtime Error

Solution code:
H, W = map(int, input().split())
s_list = []
for _ in range(H):
    s = input()
    s_list.append(s)
ans = 0
for h in range(H):
    for w in range(W):
        if s_list[h][w] == '.':
            d = deque()
            d.append([h, w])
            visited = set({})
            while d:
                i, j = d.pop()
                visited.add(str(i) + '_' + str(j))
                for ii, jj in [[1, 0], [-1, 0], [0, 1], [0, -1]]:
                    if (0 <= (i + ii) < H) & (0 <= (j + jj) < W):
                        if str(i + ii) + '_' + str(j + jj) not in visited:
                            if s_list[i][j] != s_list[i + ii][j + jj]:
                                d.append([i + ii, j + jj])
                                if s_list[i + ii][j + jj] == '#':                                    
                                    ans += 1
                            visited.add(str(i + ii) + '_' + str(j + jj))
print(ans)

Submission status: Runtime Error

Solution code:
h,w=map(int,input().split())
lists=[list(input()) for i in range(h)]
visited=[[False for i in range(h)] for j in range(w)]
from collections import deque

ans=0
dif=[(-1,0),(1,0),(0,-1),(0,1)]
def solve(i,j):
    global ans 
    ans=ans
    visited[i][j]=True
    d=deque()
    e=deque()
    d.append((i,j))
    black=0
    white=0
    while d:
        while d:
            p=d.popleft()
            x,y=p
            color=lists[x][y]
            if color=="#":
                black+=1
            else:
                white+=1
            for que in dif:
                dx,dy=que
                if 0<=dx+x<h and 0<=dy+y<w:
                    if visited[dx+x][dy+y]==False and visited[dx+x][dy+y]!=color:
                        visited[dx+x][dy+y]=True
                        e.append((dx+x,dy+y))
                        if color=="#":
                            white+=1
                        else:
                            black+=1
        if e:
            d=e
            e=deque()
    ans+=white*black
flag=True
while flag:
    sub=False
    for i in range(h):
        for j in range(w):
            if visited[i][j]==False:
                solve(i,j)
                sub=True
    if sub==False:
        flag=False
print(ans)

Submission status: Runtime Error

Solution code:
H, W = map(int, input().split())
S = []
startList = []
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
B_cnt = 0
W_cnt = 0
isReached = [[False for _ in range(W)] for __ in range(H)]
ansL = []
for i in range(H):
    s = input()
    S.append(s)
    for j in range(W):
        if s[j] == ".":
            startList.append([i, j])

def dfs(x, y, color):
    global B_cnt, W_cnt
    isReached[x][y] = True
    if color == "B":
        B_cnt += 1
    else:
        W_cnt += 1


    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]
        if 0 <= nx and nx < H and 0 <= ny and ny < W:
            if isReached[nx][ny] == False:
                if color == "B":
                    if S[nx][ny] == ".":
                        dfs(nx, ny, "W")
                else:
                    if S[nx][ny] == "#":
                        dfs(nx, ny, "B")

for start in startList:
    B_cnt = 0
    W_cnt = 0
    dfs(start[0], start[1], "W")
    ansL.append([B_cnt, W_cnt])

ans = 0

for a in ansL:
    ans += a[0] * a[1]

print(ans)

Submission status: Runtime Error

Solution code:
H, W = map(int, input().split())
S = []
startList = []
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
isReached = [[False for _ in range(W)] for __ in range(H)]
ans = 0
for i in range(H):
    s = input()
    S.append(s)
    for j in range(W):
        if s[j] == ".":
            startList.append([i, j])

def dfs(x, y, color):
    global ans
    isReached[x][y] = True
    if color == "B":
        ans += 1

    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]
        if 0 <= nx and nx < H and 0 <= ny and ny < W:
            if isReached[nx][ny] == False:
                if color == "B":
                    if S[nx][ny] == ".":
                        dfs(nx, ny, "W")
                else:
                    if S[nx][ny] == "#":
                        dfs(nx, ny, "B")

for start in startList:
    isReached = [[False for _ in range(W)] for __ in range(H)]
    dfs(start[0], start[1], "W")


print(ans)

Submission status: Runtime Error

Solution code:
H,W=map(int,input().split())
S=[input() for i in range(H)]
l=[[0]*(W+2) for i in range(H+2)]
for i in range(1,H+1):
    for j in range(1,W+1):
        l[i][j]=1
a,c=0,1
def nu(h,w):
    global c,b
    if S[h-1][w-1]=="#":
        b+=1
    if l[h-1][w] and S[h-1][w-1]!=S[h-2][w-1]:
        l[h-1][w]=0
        c+=1
        nu(h-1,w)
    if l[h+1][w] and S[h-1][w-1]!=S[h][w-1]:
        l[h+1][w]=0
        c+=1
        nu(h+1,w)
    if l[h][w-1] and S[h-1][w-1]!=S[h-1][w-2]:
        l[h][w-1]=0
        c+=1
        nu(h,w-1)
    if l[h][w+1] and S[h-1][w-1]!=S[h-1][w]:
        l[h][w+1]=0
        c+=1
        nu(h,w+1)
for i in range(1,H+1):
    for j in range(1,W+2):
        if not l[i][j]:
            continue
        b,c=0,1
        l[i][j]=0
        nu(i,j)
        a+=b*(c-b)
print(a)

Submission status: Runtime Error

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

black_visited_flag = [[False] * W for _ in range(H)] 

other_color = {".": "#", "#":'.'}

def dfs(i,j, color):
    num = 0
    black_num = 0
    #import IPython;IPython.embed()
    if i != 0:
        if S[i-1][j] == other_color[color] and not visit_flag[i-1][j]:
            visit_flag[i-1][j] = True
            _num, _black_num = dfs(i-1, j, other_color[color])
            num += _num
            black_num += _black_num
            if other_color[color] == "#":
                black_num += 1
                black_visited_flag[i-1][j] = True
            else:
                num += 1
    if i != H-1:
        if S[i+1][j] == other_color[color] and not visit_flag[i+1][j]:
            visit_flag[i+1][j] = True
            _num, _black_num = dfs(i+1, j, other_color[color])
            num += _num
            black_num += _black_num
            if other_color[color] == "#":
                black_num += 1
                black_visited_flag[i+1][j] = True
            else:
                num += 1
    if j != 0:
        if S[i][j-1] == other_color[color] and not visit_flag[i][j-1]:
            visit_flag[i][j-1] = True
            _num, _black_num = dfs(i, j -1, other_color[color])
            num += _num
            black_num += _black_num
            if other_color[color] == "#":
                black_num += 1
                black_visited_flag[i][j-1] = True
            else:
                num += 1
    if j != W-1:
        if S[i][j+1] == other_color[color] and not visit_flag[i][j+1]:
            visit_flag[i][j+1] = True
            _num, _black_num = dfs(i, j+1, other_color[color])
            num += _num
            black_num += _black_num
            if other_color[color] == "#":
                black_num += 1
                black_visited_flag[i][j+1] = True
            else:
                num += 1
    return num, black_num



ans = 0
for i, row in enumerate(S):
    for j, val in enumerate(row):
        if black_visited_flag[i][j] or S[i][j] == ".":
            continue
        visit_flag = [[False] * W for _ in range(H)] 
        num, black_num = dfs(i,j, "#")
        ans += (num * black_num)

print(ans)

Submission status: Runtime Error

Solution code:
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
 
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

H, W = MAP()
S = [input() for i in range(H)]

dx = [0, 1, 0, -1]
dy = [1, 0 ,-1, 0]
ans = 0

for h in range(H):
    for w in range(W):
        if S[h][w] == "#":
            # 0 is kouho
            q = deque([[h, w]])
            cost = [[0] * W for i in range(H)]
            visited = [[False] * W for i in range(H)]
            while q:
                # print("q:", q.popleft())
                h1, w1 = q.popleft()

                visited[h1][w1] = visited[True]
                for i in range(4):
                    h_next = h1 + dy[i]
                    w_next = w1 + dx[i]
                    if 0 <= h_next < H and 0 <= w_next < W:
                        s_next = S[h_next][w_next]
                        if s_next != S[h1][w1]:
                            if visited[h_next][w_next] == False:
                                visited[h_next][w_next] = True
                                cost[h_next][w_next] += 1
                                q.append([h_next, w_next])
            # print("******")
            # print(*cost, sep="\n")
            for h in range(H):
                for w in range(W):
                    if S[h][w] == "#":
                        ans += cost[h][w]//2
                    else:
                        ans += cost[h][w]      
            # print(ans)
# print(*cost, sep="\n")

# ans = 0
# for h in range(H):
#     for w in range(W):
#         ans += cost[h][w]
print(ans)

Submission status: Runtime Error

Solution code:
h,w=[int(j) for j in input().split()]
s=[input()for i in range(h)]
ans=0
def f(i,j,se):
    se.add((i,j))
    res=0
    b=True
    for x,y in [(1,0),(-1,0),(0,1),(0,-1)]:
        p,q=i+x,j+y
        if 0<=p<h and 0<=q<w:
            if s[p][q]!=s[i][j] and (p,q) not in se:
                b=False
                res+=f(p,q,se)
    if b:
        if s[i][j]==".":
            return 1
        else:
            return 0
    else:
        if s[i][j]==".":
            return res+1
        else:
            return res

for i in range(h):
    for j in range(w):
        if s[i][j]=="#":
            ans+=f(i,j,set())

print(ans)

Submission status: Runtime Error

Solution code:
import queue

h,w = map(int,input().split())
si = [input() for i in range(h)]

q = queue.Queue()

check = [-1]*(h*w)

#print(check,check==-1)
#exit()

vx = [0,1,0,-1]
vy = [1,0,-1,0]

def dfs(num,clr):
    #print(min(check))
    #if min(check) > -1:
    #    return
    
    y = num//w
    x = num%w
    for j in range(4):
        ny = y + vy[j]
        nx = x + vx[j]
        if ny >= 0 and ny < h and nx >= 0 and nx < w:
            new_num = ny*w+nx
            if check[new_num] != -1:
                continue
            #print(new_num,num,clr,si[ny][nx])
            if clr == '#':
                #print(ny,nx)
                if si[ny][nx] == '.':
                    check[new_num] = check[num]
                    dfs(new_num,'.')
            else:
                    
                if si[ny][nx] == '#':
                    check[new_num] = check[num]
                    dfs(new_num,'#')
            #print(check)

for i in range(h*w):
    #print(i)
    y = i//w
    x = i%w
    if si[y][x] == '#':
        if check[i] != -1:
            continue
        check[i] = i
        dfs(i,'#')
        #print(check)
        #exit()

ans = 0

li = [0]*(h*w+1)

for i in range(h):
    for j in range(w):
        if si[i][j] == '.':
            li[check[i*w+j]] += 1

#print(li)

for i in range(h):
    for j in range(w):
        if si[i][j] == '#':
            ans += li[check[i*w+j]]
            
print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np
import sys
H, W = map(int, input().split())
sys.setrecursionlimit(160000)
text = []
buf = np.zeros((H, W))
answer = 0

for i in range(0, H):
    text.append(input())

def loop(x1, y1, lasttext, is_start):
    global answer
    if(x1 < 0 or x1 >= W or y1 < 0 or y1 >= H):
        return
    if(lasttext == text[y1][x1] or buf[y1][x1] == 1):
        return
    if((not is_start) and text[y1][x1] == '#'):
        answer += 1
    buf[y1][x1] = 1
    loop(x1 + 1, y1, text[y1][x1], False)
    loop(x1 - 1, y1, text[y1][x1], False)
    loop(x1, y1 + 1, text[y1][x1], False)
    loop(x1, y1 - 1, text[y1][x1], False)
    

for y in range(0, H):
    for x in range(0, W):
        buf = np.zeros((H, W))
        if(text[y][x] == '.'):
            loop(x, y, 'x', True)

print(answer)

Submission status: Runtime Error

Solution code:
import numpy as np
import sys
H, W = map(int, input().split())
print(160000)
text = []
buf = np.zeros((H, W))
answer = 0

for i in range(0, H):
    text.append(input())

def loop(x1, y1, lasttext, is_start):
    global answer
    if(x1 < 0 or x1 >= W or y1 < 0 or y1 >= H):
        return
    if(lasttext == text[y1][x1] or buf[y1][x1] == 1):
        return
    if((not is_start) and text[y1][x1] == '#'):
        answer += 1
    buf[y1][x1] = 1
    loop(x1 + 1, y1, text[y1][x1], False)
    loop(x1 - 1, y1, text[y1][x1], False)
    loop(x1, y1 + 1, text[y1][x1], False)
    loop(x1, y1 - 1, text[y1][x1], False)
    

for y in range(0, H):
    for x in range(0, W):
        buf = np.zeros((H, W))
        if(text[y][x] == '.'):
            loop(x, y, 'x', True)

print(answer)

Submission status: Runtime Error

Solution code:
import numpy as np
import sys
H, W = map(int, input().split())
sys.setrecursionlimit(H * W)
text = []
buf = np.zeros((H, W))
answer = 0

for i in range(0, H):
    text.append(input())

def loop(x1, y1, lasttext, is_start):
    global answer
    if(x1 < 0 or x1 >= W or y1 < 0 or y1 >= H):
        return
    if(lasttext == text[y1][x1] or buf[y1][x1] == 1):
        return
    if((not is_start) and text[y1][x1] == '#'):
        answer += 1
    buf[y1][x1] = 1
    loop(x1 + 1, y1, text[y1][x1], False)
    loop(x1 - 1, y1, text[y1][x1], False)
    loop(x1, y1 + 1, text[y1][x1], False)
    loop(x1, y1 - 1, text[y1][x1], False)
    

for y in range(0, H):
    for x in range(0, W):
        buf = np.zeros((H, W))
        if(text[y][x] == '.'):
            loop(x, y, 'x', True)

print(answer)

Submission status: Runtime Error

Solution code:
import numpy as np
import sys
H, W = map(int, input().split())
sys.setrecursionlimit(H, W)
text = []
buf = np.zeros((H, W))
answer = 0

for i in range(0, H):
    text.append(input())

def loop(x1, y1, lasttext, is_start):
    global answer
    if(x1 < 0 or x1 >= W or y1 < 0 or y1 >= H):
        return
    if(lasttext == text[y1][x1] or buf[y1][x1] == 1):
        return
    if((not is_start) and text[y1][x1] == '#'):
        answer += 1
    buf[y1][x1] = 1
    loop(x1 + 1, y1, text[y1][x1], False)
    loop(x1 - 1, y1, text[y1][x1], False)
    loop(x1, y1 + 1, text[y1][x1], False)
    loop(x1, y1 - 1, text[y1][x1], False)
    

for y in range(0, H):
    for x in range(0, W):
        buf = np.zeros((H, W))
        if(text[y][x] == '.'):
            loop(x, y, 'x', True)

print(answer)

Submission status: Runtime Error

Solution code:
import numpy as np

H, W = map(int, input().split())
text = []
buf = np.zeros((H, W))
answer = 0

for i in range(0, H):
    text.append(input())

def loop(x1, y1, lasttext, is_start):
    global answer
    if(x1 < 0 or x1 >= W or y1 < 0 or y1 >= H):
        return
    if(lasttext == text[y1][x1] or buf[y1][x1] == 1):
        return
    if((not is_start) and text[y1][x1] == '#'):
        answer += 1
    buf[y1][x1] = 1
    loop(x1 + 1, y1, text[y1][x1], False)
    loop(x1 - 1, y1, text[y1][x1], False)
    loop(x1, y1 + 1, text[y1][x1], False)
    loop(x1, y1 - 1, text[y1][x1], False)
    

for y in range(0, H):
    for x in range(0, W):
        buf = np.zeros((H, W))
        if(text[y][x] == '.'):
            loop(x, y, 'x', True)

print(answer)

Submission status: Runtime Error

Solution code:
import numpy as np

H, W = map(int, input().split())
text = []
buf = np.zeros((H, W))
answer = 0

for i in range(0, H):
    text.append(input())

def loop(x1, y1, lasttext, is_start):
    global answer
    if(x1 < 0 or x1 >= W or y1 < 0 or y1 >= H):
        return
    if(lasttext == text[y1][x1] or buf[y1][x1] == 1):
        return
    if((not is_start) and text[y1][x1] == '#'):
        answer += 1
    buf[y1][x1] = 1
    loop(x1 + 1, y1, text[y1][x1], False)
    loop(x1 - 1, y1, text[y1][x1], False)
    loop(x1, y1 + 1, text[y1][x1], False)
    loop(x1, y1 - 1, text[y1][x1], False)
    

for y in range(0, H):
    for x in range(0, W):
        buf = np.zeros((H, W))
        if(text[y][x] == '.'):
            loop(x, y, 'x', True)

print(answer / 2)

Submission status: Runtime Error

Solution code:
import numpy as np

H, W = map(int, input().split())
text = []
buf = np.zeros((H, W))
answer = 0

for i in range(0, H):
    text.append(input())

def loop(x1, y1, lasttext, is_start):
    global answer
    if(x1 < 0 or x1 >= W or y1 < 0 or y1 >= H):
        return
    if(lasttext == text[y1][x1] or buf[y1][x1] == 1):
        return
    if(not is_start):
        answer += 1
    buf[y1][x1] = 1
    loop(x1 + 1, y1, text[y1][x1], False)
    loop(x1 - 1, y1, text[y1][x1], False)
    loop(x1, y1 + 1, text[y1][x1], False)
    loop(x1, y1 - 1, text[y1][x1], False)
    

for y in range(0, H):
    for x in range(0, W):
        buf = np.zeros((H, W))
        loop(x, y, 'x', True)

print(answer)

Submission status: Runtime Error

Solution code:
H, W = map(int, input().split())
text = []
answer = 0

for i in range(0, H):
    text.append(input())

def loop(x1, y1, lasttext, is_start):
    global answer
    if(x1 < 0 or x1 >= W or y1 < 0 or y1 >= H):
        return
    if(lasttext == text[y1][x1]):
        return
    if(not is_start):
        answer += 1
    loop(x1 + 1, y1, text[y1][x1], False)
    loop(x1 - 1, y1, text[y1][x1], False)
    loop(x1, y1 + 1, text[y1][x1], False)
    loop(x1, y1 - 1, text[y1][x1], False)
    

for y in range(0, H):
    for x in range(0, W):
        loop(x, y, 'x', True)

print(answer)

Submission status: Runtime Error

Solution code:
h,w = map(int,input().split())
s = [list(input()) for _ in range(h)]
visited = [[False]*w for _ in range(h)]

def dfs(y,x):
    visited[y][x] = True
    blk, wht = 0,0
    for dy,dx in zip((-1,1,0,0),(0,0,-1,1)):
        ny,nx = y+dy, x+dx
        if (not (0<=ny<h)) or (not (0<=nx<w)) or visited[ny][nx]:
            continue
        if s[y][x]!=s[ny][nx]:
            nb,nw = dfs(ny,nx)
            blk += nb
            wht += nw
    if s[y][x]=='#':
        blk += 1
    else:
        wht += 1
    return blk, wht

ans = 0
for i in range(h):
    for j in range(w):
        if not visited[i][j]:
            blk, wht = dfs(i,j)
            ans += blk*wht
print(ans)

Submission status: Runtime Error

Solution code:
black = 0
white = 0
#x,y渡すと、（ｈ、ｗ）に入ってるかどうか判定
def check(s,t):
    if (0 <=  s <= h - 1) and (0 <= t <= w - 1):
        return True
    else:
        return False

def bfs(que):
    finished = set()
    while que:
        x , y, color = que.popleft()
        if (x,y) not in finished:
            finished.add((x,y))
            for i in range(-1,2,1):
                for j in range(-1,2,1):
                    if abs(i) + abs(j) < 2 and check(y+j,x+i):
                        que.append([x+i,y+j,grid[y+j][x+i]])
                        if color != grid[y+j][x+i]:
                            adjacent_list[x+w*y].append((x + i)+w*(y + j))
def dfs(node):
    global white
    global black
    finished.add(node)
    y,x = divmod(node,w)
    if grid[y][x] == '#':
        black += 1
    else:
        white += 1
    for i in adjacent_list[node]:
        if i not in finished:
            dfs(i)
from collections import deque
h,w = map(int, input().split())
grid = []
for i in range(h):
    grid.append(list(input()))
ans = 0
adjacent_list = [[] for i in range(h*w)]
que = deque()
que.append([0,0,grid[0][0]])
bfs(que)
#再び初期化
finished = set()
for i in range(h*w):
    #頂点iからdfsをする。黒と白をカウントしておいて最後にかける
    black = 0
    white = 0
    dfs(i)
    ans += black * white
print(ans)

Submission status: Runtime Error

Solution code:
# 幅優先探索か深さ優先探索で、上下左右の隣接と異なる色ならば、連続する1つの領域とする
# 各領域ごとに、白マス数×黒マス数を計算し、その合計が答え

h, w = list(map(int, input().split()))
masu = [input() for _ in range(h)]
visited = [[False for _ in range(w)] for _ in range(h)]
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]

# とりあえず周囲の番兵は使わずに書いてみよう……

# 再帰関数の呼び出し回数が多くなる時はこれが必要！！無いとruntime errorになる。
import sys
sys.setrecursionlimit(10)

def dfs(hi, wi, white, black):
    global colors
    global dx, dy
    global visited

    # print(hi, wi)

    visited[hi][wi] = True
    if masu[hi][wi] == '.':
        white += 1
    if masu[hi][wi] == '#':
        black += 1

    for neighbor in zip(dx, dy):
        h_new = hi + neighbor[0]
        w_new = wi + neighbor[1]
        # print("new: " , h_new, w_new)
        if 0 <= h_new <= h-1 and 0 <= w_new <= w-1:
            if not visited[h_new][w_new]:
                if masu[hi][wi] != masu[h_new][w_new]:
                    white, black = dfs(h_new, w_new, white, black)
    
    return white, black

ans = 0
for hi in range(h):
    for wi in range(w):
        if not visited[hi][wi]:
            white, black = dfs(hi, wi, 0, 0)
            ans += white * black

print(ans)

Submission status: Runtime Error

Solution code:
# coding: utf-8
# Your code here!
def dfs(h,w,start):
    if S[h][w]=="#":
        black[start[0]][start[1]]+=1
    else:
        white[start[0]][start[1]]+=1
    
    visited[h][w]=1
    if h!=0:
        if visited[h-1][w]==-1 and S[h-1][w]!=S[h][w]:
            dfs(h-1,w,start)
    if w!=0:
        if visited[h][w-1]==-1 and S[h][w-1]!=S[h][w]:
            dfs(h,w-1,start)        
    if h!=H-1:
        if visited[h+1][w]==-1 and S[h+1][w]!=S[h][w]:
            dfs(h+1,w,start)        
    if w!=W-1:
        if visited[h][w+1]==-1 and S[h][w+1]!=S[h][w]:
            dfs(h,w+1,start)    
    return 

H,W=map(int,input().split())

S=[]

for _ in range(H):
    S.append(list(input()))

visited=[[-1 for j in range(W)] for i in range(H)]
black=[[0 for j in range(W)] for i in range(H)]
white=[[0 for j in range(W)] for i in range(H)]

for i in range(H):
    for j in range(W):
        if visited[i][j]==-1:
            dfs(i,j,[i,j])
        #print(visited)

ans=0
for i in range(H):
    for j in range(W):
        ans+=black[i][j]*white[i][j]
"""
print(S)
print(black)
print(white)
"""
print(ans)