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:
from functools import reduce


def main():
  h, w = map(int, input().split())
  ss = []
  for _ in range(h):
    # black(#): True, white(.): False
    ss.append([cell == '#' for cell in list(input())])

  ids = [[-1 for _ in range(w)] for _ in range(h)]
  connecteds = []
  same_id = dict()
  for i in range(h):
    for j in range(w):
      id_ = ids[i][j]
      if id_ == -1:
        connecteds.append(set([(i, j)]))
        id_ = len(connecteds) - 1
      s = connecteds[id_]
      if i < h - 1 and ss[i][j] != ss[i+1][j]:
        if ids[i+1][j] == -1:
          ids[i+1][j] = id_
          s.add((i+1, j))
        elif ids[i][j] != ids[i+1][j]:
          same_id[max(ids[i][j], ids[i+1][j])] = min(ids[i][j], ids[i+1][j])
      if j < w - 1 and ss[i][j] != ss[i][j+1]:
        if ids[i][j+1] == -1:
          ids[i][j+1] = id_
          s.add((i, j+1))
        elif ids[i][j] != ids[i][j+1]:
          same_id[max(ids[i][j], ids[i][j+1])] = min(ids[i][j], ids[i][j+1])
      connecteds[id_] = s
  for k, v in same_id.items():
    connecteds[v] = connecteds[k] | connecteds[v]
    connecteds[k] = None
  connecteds = list(filter(lambda x: x is not None, connecteds))
  ret = 0
  for conn in connecteds:
    black = sum(map(lambda ij: ss[ij[0]][ij[1]], conn))
    ret += black * (len(conn) - black)
  print(ret)


if __name__ == '__main__':
  main()

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(400*400)
from collections import Counter
def rec(union_id, i, j):
    symbol = S[i][j]
    if union_white[i][j] != 0:
        return
    if symbol == '.':
        union_white[i][j] = union_id
        next_symbol = '#'
    else:
        union_white[i][j] = -1
        next_symbol = '.'
        union_black[union_id] += 1

    if i >= 1 and S[i-1][j] == next_symbol:
        rec(union_id, i-1, j)
    if i < H-1 and S[i+1][j] == next_symbol:
        rec(union_id, i+1, j)
    if j >= 1 and S[i][j-1] == next_symbol:
        rec(union_id, i, j-1)
    if j < W-1 and S[i][j+1] == next_symbol:
        rec(union_id, i, j+1)

    return
H, W = map(int, input().split())
S = [input() for h in range(H)]
ans = 0
union_white = [[0 for w in range(W)]for h in range(H)]
union_black = Counter()
count_black = 0
for i in range(H):
    for j in range(W):
        if S[i][j] == '.' or union_white[i][j] != 0:
            continue
        count_black += 1
        rec(count_black, i, j)

counter = Counter([x for Si in union_white for x in Si])
ans = 0
# print(counter)
# print(union_black)
# print(union_white)
for i in union_black.keys():
    ans += counter[i] * union_black[i]

print(ans)

Submission status: Runtime Error

Solution code:
def dfs(x, y, c):
	d[x, y] = c
	if S[x][y] == '#':
		black[c] += 1
	else:
		white[c] += 1
	for u, v in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
		if u < 0 or u >= H or v < 0 or v >= W:
			continue
		if d[u, v] != -1:
			continue
		if S[x][y] !=  S[u][v]:
			dfs(u, v, c)

H, W = map(int, input().split())
S = []
for i in range(H):
	S.append(input())
d = {}
for i in range(H):
	for j in range(W):
		d[i, j] = -1
count = 0
black = {}
white = {}
for i in range(H):
	for j in range(W):
		if d[i, j] == -1:
			dfs(i, j, count)
			count += 1
			black[count] = 0
			white[count] = 0
ans = 0
for i in range(count):
	ans += black[i] * white[i]
print(ans)

Submission status: Runtime Error

Solution code:
h,w = map(int,input().split())
s = []
for i in range(h):
    tmp = input()
    t = []
    for j in tmp:
        if(j=='.'):
            t.append(0)
        else:
            t.append(1)
    s.append(t)

count = 0

closed_list=[]

def search(i,j,def_color):
    tmp = s[i][j]
    closed_list.append([i,j])
    a = 0
#    print(i,j)
    if i>0:
        if tmp+s[i-1][j]==1 and ([i-1,j] not in closed_list):
            if(def_color!=s[i-1][j]):
                a+=1
            a+=search(i-1,j,def_color)
    if i<h-1:
        if tmp+s[i+1][j]==1 and ([i+1,j] not in closed_list):
            if(def_color!=s[i+1][j]):
                a+=1
            a+=+search(i+1,j,def_color)
    if j>0:
        if tmp+s[i][j-1]==1 and ([i,j-1] not in closed_list):
            if(def_color!=s[i][j-1]):
                a+=1
            a+=search(i,j-1,def_color)
    if j<w-1:
        if tmp+s[i][j+1]==1 and ([i,j+1] not in closed_list):
            if(def_color!=s[i][j+1]):
                a+=1
            a+=search(i,j+1,def_color)
    return a

for i in range(h):
    for j in range(w):
        closed_list=[]
#         print('search'+str(i)+' '+str(j))
        x = s[i][j]
        count+=search(i,j,x)
        s[i][j]=-1

#         print()

print(count)

Submission status: Runtime Error

Solution code:
def dfs(x, y, c):
	d[x, y] = c
	if S[x][y] == '#':
		black[c] += 1
	else:
		white[c] += 1
	for u, v in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
		if u < 0 or u >= H or v < 0 or v >= W:
			continue
		if d[u, v] > -1:
			continue
		if S[x][y] !=  S[u][v]:
			dfs(u, v, c)

H, W = map(int, input().split())
S = []
for i in range(H):
	S.append(input())
d = {}
for i in range(H):
	for j in range(W):
		d[i, j] = -1
count = 0
black = {}
white = {}
for i in range(H):
	for j in range(W):
		if d[i, j] == -1:
			dfs(i, j, count)
			count += 1
			black[count] = 0
			white[count] = 0
ans = 0
for i in range(count):
	ans += black[i] * white[i]
print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np

H,W = [int(i) for i in input().split()]
S = np.empty([H,W])
for i in range(H):
    s = input()
    for j in range(W):
        if s[j] == '#':
            S[i,j] = 0
        else:
            S[i,j] = 1

class sagasu():
    def __init__(self,H,W,S):
        self.H = H
        self.W = W
        self.S = S
        self.num = 0

    def __call__(self):
        for i in range(self.H):
            for j in range(self.W):
                self.rireki = []
                if self.S[i,j] == 0:
                    self.bunki(i,j,0)
        return(self.num)

    def bunki(self,y,x,atai):
        self.ue(y-1,x,atai)
        self.sita(y+1,x,atai)
        self.hidari(y,x-1,atai)
        self.migi(y,x+1,atai)

    def ue(self,y,x,atai):
        if y >= 0:
            if '{}-{}'.format(y,x) not in self.rireki:
                self.rireki.append('{}-{}'.format(y,x))
                if self.S[y,x] == 1 - atai:
                    if 1 - atai == 1:
                        self.num += 1
                    self.bunki(y,x,1-atai)

    def sita(self,y,x,atai):
        if y <= self.H-1:
            if '{}-{}'.format(y,x) not in self.rireki:
                self.rireki.append('{}-{}'.format(y,x))
                if self.S[y,x] == 1 - atai:
                    if 1 - atai == 1:
                        self.num += 1
                    self.bunki(y,x,1-atai)

    def hidari(self,y,x,atai):
        if x >= 0:
            if '{}-{}'.format(y,x) not in self.rireki:
                self.rireki.append('{}-{}'.format(y,x))
                if self.S[y,x] == 1 - atai:
                    if 1 - atai == 1:
                        self.num += 1
                    self.bunki(y,x,1-atai)

    def migi(self,y,x,atai):
        if x <= self.W-1:
            if '{}-{}'.format(y,x) not in self.rireki:
                self.rireki.append('{}-{}'.format(y,x))
                if self.S[y,x] == 1 - atai:
                    if 1 - atai == 1:
                        self.num += 1
                    self.bunki(y,x,1-atai)

map = sagasu(H,W,S)
num = map()

print(num)

Submission status: Runtime Error

Solution code:
c=0
x=[-1,0,1,0]
y=[0,-1,0,1]
buf=[]
p=0
def count(h,w,S,table,H,W):
    global buf,x,y,p
    if buf or p==0:
        for i in range(4):
            if h+y[i]>=0 and h+y[i]<H and w+x[i]>=0 and w+x[i]<W:
                if table[h+y[i]][w+x[i]]==-1:
                    if S[h][w]=='.' and S[h+y[i]][w+x[i]]=='#':
                        table[h+y[i]][w+x[i]]=table[h][w]+1
                        buf.append([h+y[i],w+x[i]])
                    elif S[h][w]=='#' and S[h+y[i]][w+x[i]]=='.':
                        table[h+y[i]][w+x[i]]=table[h][w]+1
                        buf.append([h+y[i],w+x[i]])
        if buf:
            a=buf.pop(0)
            count(a[0],a[1],S,table,H,W)
    elif not(buf) and p==0:
        p+=1
        count(h,w,S,table,H,W)

H,W=map(int,input().split())
S=[]
for i in range(H):
    S.append(input())
for h in range(H):
    for w in range(W):
        if S[h][w]=='#':
            table=[[-1 for j in range(W)]for i in range(H)]
            table[h][w]=0
            count(h,w,S,table,H,W)
            for k in range(H):
                for l in range(W):
                    if table[k][l]%2==1 and table[k][l]!=-1:
                        c+=1
print(c)

Submission status: Runtime Error

Solution code:
from collections import Counter
def rec(union_id, i, j):
    symbol = S[i][j]
    if union_white[i][j] != 0:
        return
    if symbol == '.':
        union_white[i][j] = union_id
        next_symbol = '#'
    else:
        union_white[i][j] = -1
        next_symbol = '.'
        union_black[union_id] += 1

    if i >= 1 and S[i-1][j] == next_symbol:
        rec(union_id, i-1, j)
    if i < H-1 and S[i+1][j] == next_symbol:
        rec(union_id, i+1, j)
    if j >= 1 and S[i][j-1] == next_symbol:
        rec(union_id, i, j-1)
    if j < W-1 and S[i][j+1] == next_symbol:
        rec(union_id, i, j+1)

    return
H, W = map(int, input().split())
S = [input() for h in range(H)]
ans = 0
union_white = [[0 for w in range(W)]for h in range(H)]
union_black = Counter()
count_black = 0
for i in range(H):
    for j in range(W):
        if S[i][j] == '.' or union_white[i][j] != 0:
            continue
        count_black += 1
        rec(count_black, i, j)

counter = Counter([x for Si in union_white for x in Si])
ans = 0
# print(counter)
# print(union_black)
# print(union_white)
for i in union_black.keys():
    ans += counter[i] * union_black[i]

print(ans)

Submission status: Runtime Error

Solution code:
# %%time
import numpy as np
h, w = list(map(int, input().split()))
ss = []
for k in range(h):
    s = input()
    ss.append(s)

field = np.zeros([h, w])
for hk in range(h):
    for wk in range(w):
        field[hk,wk] = ss[hk][wk] == '.'
import numpy as np

# %%time

# h = 400
# w = 400
# field = np.random.randint(0,2,size = (h, w))

right = np.zeros_like(field)
right[:,:-1] = field[:,:-1] - field[:,1:] != 0
left = np.zeros_like(field)
left[:,1:] = field[:,1:] - field[:,:-1] != 0
down = np.zeros_like(field)
down[:-1,:] = field[:-1,:] - field[1:,:] != 0
up = np.zeros_like(field)
up[1:,:] = field[1:,:] - field[:-1,:] != 0

ans = {}
from itertools import product
for hk1, wk1 in product(range(h), range(w)):
    ans[(hk1, wk1)] = set()
    if right[hk1, wk1]:
        ans[(hk1, wk1)].add((hk1, wk1 + 1))
    if left[hk1, wk1]:
        ans[(hk1, wk1)].add((hk1, wk1 - 1))
    if up[hk1, wk1]:
        ans[(hk1, wk1)].add((hk1 - 1, wk1))
    if down[hk1, wk1]:
        ans[(hk1, wk1)].add((hk1 + 1, wk1))

def check(start, kidoku, a):
    a += 1
    nex = ans[start]
    ikeru = []
    for n in nex:
        if n in kidoku:
            pass
        else:
            kidoku.append(n)
            ikeru.append(n)
            ikeru += check(n, kidoku, a)
    return ikeru

s = 0
ends = {}
for hk1, wk1 in product(range(h), range(w)):
    if field[hk1,wk1] == 0:
        if (hk1, wk1) in ends.keys():
            s_here = ends[hk1, wk1]
        else:
            s_here = 0
            lis = check((hk1,wk1), [], 0)
            for l in lis:
                if field[l[0],l[1]] == 1:
                    s_here += 1
                ends[l] = s_here
#         if s_here > 0:
#             print(hk1, wk1, s_here)
        s += s_here
print(s)

Submission status: Runtime Error

Solution code:
h, w = map(int,raw_input().split())
oarr = [[] for i in range(h)]
blacks = []
for i in range(h):
    s = raw_input()
    for j in range(w):
        if s[j] == "#":
            oarr[i].append(1)
            blacks.append([i,j])
        else:
            oarr[i].append(0)
dire = [[1,0],[-1,0],[0,1],[0,-1]]
target = 1
ans = 0


def dfs(x,y):
    global target, ans, length
    if arr[x][y] != 2 and arr[x][y] == target:
        # copy = target
        if target == 0:
            if [x,y] not in cp_arr:
                cp_arr.append([x,y])
                ans += 1
        # print "target:", target, "x, y:", "(", x, ",", y,")", "ans:", ans
        target = 1 - target
        length += 1
        arr[x][y] = 2
        for cp in dire:
            if 0 <= x+cp[0] <= h-1 and 0 <= y+cp[1] <= w-1:
                dfs(x+cp[0],y+cp[1])
        # if copy == 0:
        #     arr[x][y] = copy
        target = 1 - target
        return
    return

for each_cp in blacks:
    length = 0
    cp_arr = []
    arr = [[] for i in range(h)]
    for i in range(h):
        for j in range(w):
            arr[i].append(oarr[i][j])
    dfs(each_cp[0], each_cp[1])
    # print "--------------"
    # print arr

print ans

Submission status: Runtime Error

Solution code:
H,W = map(int,input().split(' '))
S = []
for i in [0]*H:
	l = input()
	S.append([1 if x == '#' else -1 for x in l])
#c = [[False]*W for i in range(H)]

def check(S,x,y):
	global bk
	global wh
	if S[y][x] == 0:
		return
	if S[y][x] == 1:
		S[y][x]=0
		if 0 < y and S[y-1][x] == -1:
			check(S,x,y-1)
		if 0 < x and S[y][x-1] == -1:
			check(S,x-1,y)
		if y < H-1 and S[y+1][x] == -1:
			check(S,x,y+1)
		if x < W-1 and S[y][x+1] == -1:
			check(S,x+1,y)
		bk += 1
	else:
		wh += 1
		S[y][x]=0
		if 0 < y and S[y-1][x] == 1:
			check(S,x,y-1)
		if 0 < x and S[y][x-1] == 1:
			check(S,x-1,y)
		if y < H-1 and S[y+1][x] == 1:
			check(S,x,y+1)
		if x < W-1 and S[y][x+1] == 1:
			check(S,x+1,y)
	return

cnt = 0
bk = 0
wh = 0
for y in range(H):
	for x in range(W):
		if S[y][x] == 1:
			check(S,x,y)
			cnt += wh*bk
			wh = 0
			bk = 0
print(cnt)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(400*400*400*400)

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

mask = ["".join(["#" if (i + j) % 2 else "." for j in range(W)]) for i in range(H)]

masked_S = [[1 if S[i][j] == mask[i][j] else 0 for j in range(W)] for i in range(H)]

S_colored = [[-1 for j in range(W)] for i in range(H)]

color_count = dict()


def fill(i, j, color):
    S_colored[i][j] = color

    if S[i][j] == "#":
        color_count[color][0] += 1
    else:
        color_count[color][1] += 1

    for yx in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
        dy, dx = yx
        i2, j2 = i + dy, j + dx

        if i2 < 0 or i2 >= H or j2 < 0 or j2 >= W:
            continue

        if S_colored[i2][j2] != -1:
            continue

        if masked_S[i2][j2] != masked_S[i][j]:
            continue

        fill(i2, j2, color)


def main():
    color = -1
    for i in range(H):
        for j in range(W):
            if S_colored[i][j] != -1:
                continue
            color += 1
            color_count[color] = [0, 0]
            fill(i, j, color)

    result = 0
    for k in color_count.keys():
        result += color_count[k][0] * color_count[k][1]

    print(result)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import itertools
import sys
sys.setrecursionlimit(100000)
h, w = map(int, input().split())
s_list = []
for i in range(h):
  s_list.append(list(input()))
res = 0
check_list = set()

def rec_create_area(point, tmp_area, current_str):
  new_point_list = []
  new_point_list.append((point[0] + 1, point[1]))
  new_point_list.append((point[0], point[1] + 1))
  new_point_list.append((point[0] - 1, point[1]))
  new_point_list.append((point[0], point[1] - 1))
  for new_point in new_point_list:
    if new_point[0] >= h or new_point[1] >= w or new_point[0] < 0 or new_point[1]  < 0:
      continue
    if new_point in check_list:
      continue
    new_str = s_list[new_point[0]][new_point[1]]
    if new_str == current_str:
      continue
    if new_str == "#":
      tmp_area[0] += 1
    else:
      tmp_area[1] += 1
    check_list.add(new_point)
    rec_create_area(new_point, tmp_area, new_str)
  
for a, b in itertools.product(range(h), range(w)):
  check_point = (a, b)
  if check_point in check_list:
    continue
  check_list.add(check_point)
  current_str = s_list[check_point[0]][check_point[1]]
  if current_str == "#":
    tmp_area = [1, 0]
  else:
    tmp_area = [0, 1]
  rec_create_area(check_point, tmp_area, current_str)
  res += tmp_area[0] * tmp_area[1]
  
print(res)

Submission status: Runtime Error

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

#white = ".", black = "#"
def search(x, y, color):
    global ans
    if color == ".":
        for m in [1, -1]:
            if 0 <= x+m <= H-1:
                if S[x+m][y] == "#" and not dp[x+m][y]:
                    dp[x+m][y] = True
                    color = "#"
                    search(x+m, y, color)
        for n in [1, -1]:
            if 0 <= y+n <= W-1:
                if S[x][y+n] == "#" and not dp[x][y+n]:
                    dp[x][y+n] = True
                    color = "#"
                    search(x, y+n, color)

    else:
        for m in [1, -1]:
            if 0 <= x+m <= H-1:
                if S[x+m][y] == "." and not dp[x+m][y]:
                    ans += 1
                    dp[x+m][y] = True
                    color = "."
                    search(x+m, y, color)

        for n in [1, -1]:
            if 0 <= y+n <= W-1:
                if S[x][y+n] == "." and not dp[x][y+n]:
                    ans += 1
                    dp[x][y+n] = True
                    color = "."
                    search(x, y+n, color)


ans = 0
for i in range(H):
    for j in range(W):
        if S[i][j] == "#":
            dp = [[False] * W for a in range(H)]
            dp[i][j] = True
            search(i, j, "#")

print(ans)

Submission status: Runtime Error

Solution code:
h, w = [int(i) for i in input().split()]
s = [input() for i in range(h)]
cnt = 0
e = []
def ahaha(i, j):
    global cnt
    global e
    e.append([i,j])
    if i+1 < h:
        if s[i+1][j] != s[i][j]:
            if [i+1,j] not in e:
                if s[i+1][j] == ".":
                    cnt += 1
                ahaha(i+1,j)
    if i-1 >= 0:
        if s[i-1][j] != s[i][j]:
            if [i-1,j] not in e:
                if s[i-1][j] == ".":
                    cnt += 1
                ahaha(i-1,j)
    if j+1 < w:
        if s[i][j+1] != s[i][j]:
            if [i,j+1] not in e:
                if s[i][j+1] == ".":
                    cnt += 1
                ahaha(i,j+1)
    if j-1 >= 0:
        if s[i][j-1] != s[i][j]:
            if [i,j-1] not in e:
                if s[i][j-1] == ".":
                    cnt += 1
                ahaha(i,j-1)

for i in range(h):
    for j in range(w):
        if s[i][j] == "#":
            ahaha(i,j)
            e = []
print(cnt)

Submission status: Runtime Error

Solution code:
import itertools
import sys
sys.setrecursionlimit(10000)
h, w = map(int, input().split())
s_list = []
for i in range(h):
  s_list.append(list(input()))
res = 0
check_list = set()

def rec_create_area(point, tmp_area, current_str):
  new_point_list = []
  new_point_list.append((point[0] + 1, point[1]))
  new_point_list.append((point[0], point[1] + 1))
  new_point_list.append((point[0] - 1, point[1]))
  new_point_list.append((point[0], point[1] - 1))
  for new_point in new_point_list:
    if new_point[0] >= h or new_point[1] >= w or new_point[0] < 0 or new_point[1]  < 0:
      continue
    if new_point in check_list:
      continue
    new_str = s_list[new_point[0]][new_point[1]]
    if new_str == current_str:
      continue
    if new_str == "#":
      tmp_area[0] += 1
    else:
      tmp_area[1] += 1
    check_list.add(new_point)
    rec_create_area(new_point, tmp_area, new_str)
  
for a, b in itertools.product(range(h), range(w)):
  check_point = (a, b)
  if check_point in check_list:
    continue
  check_list.add(check_point)
  current_str = s_list[check_point[0]][check_point[1]]
  if current_str == "#":
    tmp_area = [1, 0]
  else:
    tmp_area = [0, 1]
  rec_create_area(check_point, tmp_area, current_str)
  res += tmp_area[0] * tmp_area[1]
  
print(res)

Submission status: Runtime Error

Solution code:
before = 0
for i, raw in enumerate(b_list):
    for j in raw:
         before += len(res[i][j])
while True:
    for i, raw in enumerate(b_list):
        for j in raw:
            try:
                if S[i-1][j] == '.' or S[i][j-1] == '.':
                    res[i][j] += res[i-1][j-1]
            except:
                pass
            try:
                if S[i+1][j] == '.' or S[i][j-1] == '.':
                    res[i][j] += res[i+1][j-1]
            except:
                pass
            try:
                if S[i-1][j] == '.' or S[i][j+1] == '.':
                    res[i][j] += res[i-1][j+1]
            except:
                pass
            try:
                if S[i+1][j] == '.' or S[i][j+1] == '.':
                    res[i][j] += res[i+1][j+1]
            except:
                pass
    before = result
    for i, raw in enumerate(b_list):
        for j in raw:
            res[i][j] = list(set(res[i][j]))
    result = 0
    for i, raw in enumerate(b_list):
        for j in raw:
             result += len(res[i][j])
    if before == result:
        break
print(result)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(400*400)

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

mask = ["".join(["#" if (i + j) % 2 else "." for j in range(W)]) for i in range(H)]

masked_S = [[1 if S[i][j] == mask[i][j] else 0 for j in range(W)] for i in range(H)]

S_colored = [[-1 for j in range(W)] for i in range(H)]

color_count = dict()


def fill(i, j, color):
    S_colored[i][j] = color

    if S[i][j] == "#":
        color_count[color][0] += 1
    else:
        color_count[color][1] += 1

    for yx in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
        dy, dx = yx
        i2, j2 = i + dy, j + dx

        if i2 < 0 or i2 >= H or j2 < 0 or j2 >= W:
            continue

        if S_colored[i2][j2] != -1:
            continue

        if masked_S[i2][j2] != masked_S[i][j]:
            continue

        fill(i2, j2, color)


def main():
    color = -1
    for i in range(H):
        for j in range(W):
            if S_colored[i][j] != -1:
                continue
            color += 1
            color_count[color] = [0, 0]
            fill(i, j, color)

    result = 0
    for k in color_count.keys():
        result += color_count[k][0] * color_count[k][1]

    print(result)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
def dfs(x, y, c):
	d[x, y] = c
	if S[x][y] == '#':
		black[c] += 1
	else:
		white[c] += 1
	for u, v in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
		if u < 0 or u >= H or v < 0 or v >= W:
			continue
		if d[u, v] != -1:
			continue
		if S[x][y] !=  S[u][v]:
			dfs(u, v, c)

H, W = map(int, input().split())
S = []
for i in range(H):
	S.append(input())
d = {}
for i in range(H):
	for j in range(W):
		d[i, j] = -1
count = 0
black = {}
white = {}
for i in range(H):
	for j in range(W):
		black[i * W + j] = 0
		white[i * W + j] = 0
		if d[i, j] == -1:
			dfs(i, j, count)
			count += 1
ans = 0
for i in range(count):
	ans += black[i] * white[i]
print(ans)

Submission status: Runtime Error

Solution code:
import itertools
import sys
sys.setrecursionlimit(2000)
h, w = map(int, input().split())
s_list = []
for i in range(h):
  s_list.append(list(input()))
res = 0
check_list = set()

def rec_create_area(point, tmp_area, current_str):
  new_point_list = []
  new_point_list.append((point[0] + 1, point[1]))
  new_point_list.append((point[0], point[1] + 1))
  new_point_list.append((point[0] - 1, point[1]))
  new_point_list.append((point[0], point[1] - 1))
  for new_point in new_point_list:
    if new_point[0] >= h or new_point[1] >= w or new_point[0] < 0 or new_point[1]  < 0:
      continue
    if new_point in check_list:
      continue
    new_str = s_list[new_point[0]][new_point[1]]
    if new_str == current_str:
      continue
    if new_str == "#":
      tmp_area[0] += 1
    else:
      tmp_area[1] += 1
    check_list.add(new_point)
    rec_create_area(new_point, tmp_area, new_str)
  
for a, b in itertools.product(range(h), range(w)):
  check_point = (a, b)
  if check_point in check_list:
    continue
  check_list.add(check_point)
  current_str = s_list[check_point[0]][check_point[1]]
  if current_str == "#":
    tmp_area = [1, 0]
  else:
    tmp_area = [0, 1]
  rec_create_area(check_point, tmp_area, current_str)
  res += tmp_area[0] * tmp_area[1]
  
print(res)

Submission status: Runtime Error

Solution code:
h, w = map(int,raw_input().split())
oarr = [[] for i in range(h)]
blacks = []
for i in range(h):
    s = raw_input()
    for j in range(w):
        if s[j] == "#":
            oarr[i].append(1)
            blacks.append([i,j])
        else:
            oarr[i].append(0)
dire = [[1,0],[-1,0],[0,1],[0,-1]]
target = 1
ans = 0


def dfs(x,y):
    global target, ans, length
    if arr[x][y] != 2 and arr[x][y] == target:
        copy = target
        if target == 0:
            if [x,y] not in cp_arr:
                cp_arr.append([x,y])
                ans += 1
        # print "target:", target, "x, y:", "(", x, ",", y,")", "ans:", ans
        target = 1 - target
        length += 1
        arr[x][y] = 2
        for cp in dire:
            if 0 <= x+cp[0] <= h-1 and 0 <= y+cp[1] <= w-1:
                dfs(x+cp[0],y+cp[1])
        if copy == 0:
            arr[x][y] = copy
        target = 1 - target
        return
    return

for each_cp in blacks:
    length = 0
    cp_arr = []
    arr = [[] for i in range(h)]
    for i in range(h):
        for j in range(w):
            arr[i].append(oarr[i][j])
    dfs(each_cp[0], each_cp[1])
    # print "--------------"
    # print arr

print ans

Submission status: Runtime Error

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

mask = ["".join(["#" if (i + j) % 2 else "." for j in range(W)]) for i in range(H)]

masked_S = [[1 if S[i][j] == mask[i][j] else 0 for j in range(W)] for i in range(H)]

S_colored = [[-1 for j in range(W)] for i in range(H)]

color_count = dict()


def fill(i, j, color):
    S_colored[i][j] = color

    if S[i][j] == "#":
        color_count[color][0] += 1
    else:
        color_count[color][1] += 1

    for yx in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
        dy, dx = yx
        i2, j2 = i + dy, j + dx

        if i2 < 0 or i2 >= H or j2 < 0 or j2 >= W:
            continue

        if S_colored[i2][j2] != -1:
            continue

        if masked_S[i2][j2] != masked_S[i][j]:
            continue

        fill(i2, j2, color)


def main():
    color = -1
    for i in range(H):
        for j in range(W):
            if S_colored[i][j] != -1:
                continue
            color += 1
            color_count[color] = [0, 0]
            fill(i, j, color)

    result = 0
    for k in color_count.keys():
        result += color_count[k][0] * color_count[k][1]

    print(result)

if __name__ == '__main__':
    main()

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 bfs(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]['#'] = count[p * H + q].get('#', 0)
        count[p * H + q]['.'] = count[p * H + q].get('.', 0)
        count[p * H + q][S[x][y]] += 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] and A[nx][ny] == 0:
                    bfs(nx, ny, p, q)


for i, j in itertools.product(range(H), range(W)):
    bfs(i, j, i, j)
ans = 0
if count:
    for i in count:
        ans += count[i].get('#', 0) * count[i].get('.', 0)
print(ans)

Submission status: Runtime Error

Solution code:
h,w = map(int,input().split())
s = []
for i in range(h):
    tmp = input()
    t = []
    for j in tmp:
        if(j=='.'):
            t.append(0)
        else:
            t.append(1)
    s.append(t)

count = 0

closed_list=[]

def search(i,j,def_color):
    tmp = s[i][j]
    closed_list.append([i,j])
    a = 0
#    print(i,j)
    if i>0:
        if tmp+s[i-1][j]==1 and ([i-1,j] not in closed_list):
            if(def_color!=s[i-1][j]):
                a+=1
            a+=search(i-1,j,def_color)
    if i<h-1:
        if tmp+s[i+1][j]==1 and ([i+1,j] not in closed_list):
            if(def_color!=s[i+1][j]):
                a+=1
            a+=+search(i+1,j,def_color)
    if j>0:
        if tmp+s[i][j-1]==1 and ([i,j-1] not in closed_list):
            if(def_color!=s[i][j-1]):
                a+=1
            a+=search(i,j-1,def_color)
    if j<w-1:
        if tmp+s[i][j+1]==1 and ([i,j+1] not in closed_list):
            if(def_color!=s[i][j+1]):
                a+=1
            a+=search(i,j+1,def_color)
    return a

for i in range(h):
    for j in range(w):
         closed_list=[]
#         print('search'+str(i)+' '+str(j))
         count+=search(i,j,s[i][j])
         s[i][j]=-1
#         print()

print(count)

Submission status: Runtime Error

Solution code:
def count(i,j):
    global h,w,s1,ans
    a=s1[i][j]
    s1[i][j]=0
    if i-1>=0:
        if s1[i-1][j]!=0 and s1[i-1][j]!=a:
            if s1[i-1][j]=='.':
                ans+=1
            count(i-1,j)
    if i+1<h:
        if s1[i+1][j]!=0 and s1[i+1][j]!=a:
            if s1[i+1][j]=='.':
                ans+=1
            count(i+1,j)
    if j-1>=0:
        if s1[i][j-1]!=0 and s1[i][j-1]!=a:
            if s1[i][j-1]=='.':
                ans+=1
            count(i,j-1)
    if j+1<w:
        if s1[i][j+1]!=0 and s1[i][j+1]!=a:
            if s1[i][j+1]=='.':
                ans+=1
            count(i,j+1)

import copy
h,w=map(int,input().split())
s=[]
for i in range(h):
    s.append(list(input()))
ans=0
for i in range(h):
    for j in range(w):
        if s[i][j]=='#':
            s1=copy.deepcopy(s)
            count(i,j)
print(int(ans))