Problem:


Score : 300 points

Problem Statement

You are given a grid of squares with H horizontal rows and W vertical columns, where each square is painted white or black.
HW characters from A_{11} to A_{HW} represent the colors of the squares.
A_{ij} is # if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is . if that square is white.

We will repeatedly perform the following operation until all the squares are black:

Every white square that shares a side with a black square, becomes black.

Find the number of operations that will be performed.
The initial grid has at least one black square.

Constraints

1 \leq H,W \leq 1000

A_{ij} is # or ..

The given grid has at least one black square.

Input

Input is given from Standard Input in the following format:

H W
A_{11}A_{12}...A_{1W}
:
A_{H1}A_{H2}...A_{HW}

Output

Print the number of operations that will be performed.

Sample Input 1

3 3
...
.#.
...

Sample Output 1

2

After one operation, all but the corners of the grid will be black. After one more operation, all the squares will be black.

Sample Input 2

6 6
..#..#
......
#..#..
......
.#....
....#.

Sample Output 2

3



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


Sample output:
2

Submission status: Runtime Error

Solution code:

def input_from_console():
    h, w = map(int, input().split())
    m = list()
    for i in range(h):
        m.append(list(input()))

    return h, w, m


def get_count(h, w, m):
    count = 0
    for i in range(h):
        count += sum([1 for item in m[i] if item == '#'])
    return count


def check(i, j, m, h, w):
    for ii in [-1, 1]:
        if i + ii < 0 or i + ii > w - 1:
            continue
        if m[i + ii][j] == "#":
            return True

    for jj in [-1, 1]:
        if j + jj < 0 or j + jj > h - 1:
            continue
        if m[i][j + jj] == "#":
            return True
    return False


def main():
    h, w, m = input_from_console()
    total = h * w
    count = 0

    while True:
        flip_list = []
        for i in range(h):
            for j in range(w):
                if m[i][j] != '#' and check(i, j, m, h, w):
                    flip_list.append([i,j])
                    # print(flip_list)
        for item in flip_list:
            m[item[0]][item[1]] = '#'
        count += 1
        # print("count", count, get_count(h, w, m), m)
        if get_count(h, w, m) == total:
            print(count)
            break


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
H,W = map(int,input().split())
A = [[i for i in input()] for _ in range(H)]
d = []
for i in range(H):
    for j in range(W):
        if(A[i][j]=='#'):
            black.append([i,j])
for i in range(H):
    for j in range(W):
        if(A[i][j]=='.'):
            d.append(min([abs(i-p[0])+abs(j-p[1]) for p in black]))
print(max(d))

Submission status: Runtime Error

Solution code:
import numpy as np


def main():
    H, W = [map(int, x) for x in input().split()]
    board = [[0 for i in range(H)] for j in range(W)]

    """ #は1, .は0 """
    for i in range(H):
        X = input()
        for j in range(len(X)):
            if X[j] == "#":
                board[i][j] = 1

    num_board = np.array(board)
    height, width = num_board.shape[:2]
    count = 0
    height_r, width_r = range(height), range(width)
    while (np.sum(num_board) != height*width):
        num_board_ans = np.zeros((height, width))
        for i in height_r:
            for j in width_r:
                if num_board[i, j] == 1:
                    num_board_ans[i, j] = 1
                    a = max(i-1, 0)
                    num_board_ans[a, j] = 1
                    b = max(j-1, 0)
                    num_board_ans[i, b] = 1
                    c = min(i+1, height-1)
                    num_board_ans[c, j] = 1
                    d = min(j+1, width-1)
                    num_board_ans[i, d] = 1
        num_board = num_board_ans
        count += 1

    print(count)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
H, W = tuple(map(int, input().split()))

P = [[-int(i) for i in input().replace("#", "0").replace(".", "1")]
     for i in range(H)]

queue_set = set()
for h in range(H):
    for w in range(W):
        if P[h][w] == 0:
            for dh, dw in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                if 0 <= h+dh < H and 0 <= w+dw < W and P[h+dh][w+dw] == -1:
                    queue_set.add((h+dh)*W+w+dw)
        elif h == 0 or h == H-1 or w == 0 or w == W-1:
            queue_set.add(h*W+w)
m = 0

queue = [[q//W, q % W, 0] for q in queue_set]
idx = 0
while len(queue) != idx+1:
    h, w, cnt = queue[idx]
    idx += 1
    if P[h][w] == -1:
        P[h][w] = cnt+1
        a = 0
        for dh, dw in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
            if 0 <= h+dh < H and 0 <= w+dw < W:
                a = max(P[h+dh][w+dw], a)
                if P[h+dh][w+dw] == -1:
                    queue += [[h+dh, w+dw, cnt+1]]
        m = max(m, cnt+1 + a)

print(m)

Submission status: Runtime Error

Solution code:
# coding:utf-8

if __name__=='__main__':
  # input
  H,W = map(int, input().split())
  A = [['.' for i in range(H+2)] for j in range(W+2)]
  B = [(i+1,j+1) for i in range(H) for j in range(W)]
  C =[]
  for i in range(H):
    input_list = input()
    for j in range(W):
      A[i+1][j+1]= input_list[j]
      
  # process
  for k in range(H+W):
    for b in B[:]:
      l, m = b
      if A[l][m]=='#':
        B.remove(b)
      elif A[l-1][m]=='#' or A[l][m-1]=='#' or A[l+1][m]=='#' or A[l][m+1]=='#':
        C.append(b)
    for c in C[:]:
      l, m = c
      A[l][m]='#'
      C.remove(c)
    if len(B)==0:
      print(k)
      break;

Submission status: Runtime Error

Solution code:
h,w=map(int,input().split())
a=[list(input()) for i in range(h)]
brack1=[]
brack2=[]
for j in range(h):
    tmp=[i for i, x in enumerate(a[j]) if x == '#']
    [brack1.append(k+1+j+1) for k in tmp]
    [brack2.append(w-k + j + 1) for k in tmp]

brack1=sorted(list(set(brack1)))
brack2=sorted(list(set(brack2)))

brack1.append(h+w+1)
brack2.append(h+w+1)

if len(brack1)>=len(brack2):
    B=len(brack1)
else:
    B=len(brack2)

b=1
c=1
ans=0
for i in range(B):
    if i < len(brack1):
        if brack1[i]-b-1>ans:
            ans=brack1[i]-b-1
    b=brack1[i]
    if i<len(brack2):
        if brack2[i]-c-1>ans:
            ans=brack2[i]-c-1
    c=brack2[i]

print(ans)

Submission status: Runtime Error

Solution code:
import copy
H,W = map(int,input().split())
A = []
B = []
for i in range(W):
    A.append([])
    B.append([])
for i in range(W):
    A[i] = list(input())
found = False
k = -1
B = copy.deepcopy(A)
while not found:
    found = True
    k += 1
    for i in range(W):
        for j in range(H):
            if A[i][j] == ".":
                found = False
                if i == 0:
                    if j == 0:
                        if A[i+1][j] =="#" or A[i][j+1] == "#":
                            B[i][j] = "#"
                    elif j == H-1:
                        if A[i+1][j] == "#" or A[i][j-1] == "#":
                            B[i][j] ="#"
                    else:
                        if A[i][j-1] == "#" or A[i][j+1] == "#" or A[i+1][j] == "#":
                            B[i][j] = "#"
                elif i == W-1:
                    if j == 0:
                        if A[i-1][j] =="#" or A[i][j+1] == "#":
                            B[i][j] = "#"
                    elif j == H-1:
                        if A[i-1][j] == "#" or A[i][j-1] == "#":
                            B[i][j] = "#"
                    else:
                        if A[i][j-1] == "#" or A[i][j+1] == "#" or A[i-1][j] == "#":
                            B[i][j] = "#"
                elif j == 0:
                    if A[i+1][j] == "#" or A[i][j+1] == "#" or A[i-1][j] == "#":
                            B[i][j] = "#"
                elif j == W-1:
                    if A[i+1][j] == "#" or A[i][j-1] == "#" or A[i-1][j] == "#":
                            B[i][j] = "#"
                else:
                    if A[i+1][j] == "#" or A[i][j-1] == "#" or A[i-1][j] == "#" or A[i][j+1] == "#":
                            B[i][j] ="#"
    A = copy.deepcopy(B)
print(k)

Submission status: Runtime Error

Solution code:
import numpy as np


def main():
    H, W = [int(x) for x in input().split()]
    board = [[0 for i in range(H)] for j in range(W)]

    """ #は1, .は0 """
    for i in range(H):
        X = input()
        for j in range(len(X)):
            if X[j] == "#":
                board[i][j] = 1

    num_board = np.array(board)
    height, width = num_board.shape[:2]
    count = 0
    height_r, width_r = range(height), range(width)
    for _ in height*width:
        num_board_ans = np.zeros((height, width))
        for i in height_r:
            for j in width_r:
                if num_board[i, j] == 1:
                    num_board_ans[i, j] = 1
                    a = max(i-1, 0)
                    num_board_ans[a, j] = 1
                    b = max(j-1, 0)
                    num_board_ans[i, b] = 1
                    c = min(i+1, height-1)
                    num_board_ans[c, j] = 1
                    d = min(j+1, width-1)
                    num_board_ans[i, d] = 1
        num_board = num_board_ans
        count += 1
        if (np.sum(num_board) == height*width):
            break

    print(count)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import numpy as np
H, W = map(int, input().split())

A = [list(map(lambda x: x == "#", input())) for i in range(H)]
A = np.array(A)
black = np.concatenate(np.where(A)).reshape(2,-1)

here = np.concatenate(np.meshgrid(np.arange(H), np.arange(W))).reshape(2, -1)
dist = np.abs(black[:, None] - here[:, :, None])
dist = dist.sum(axis=0).min(axis=1).max()
print(dist)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
import sys
import bisect
import heapq

def solve(H: int, W: int, A: "List[str]"):
    Q = []
    marked = [[0] * W for h in range(H)]
    for h in range(H):
        for w in range(W):
            if A[h][w] == '#':
                heapq.heappush(Q, (0, h, w))
                marked[h][w] = 1
    dmax = 0
    while len(Q) > 0:
        d, h, w = heapq.heappop(Q)
        dmax = max(d, dmax)
        for hh, ww in [(h-1, w), (h+1, w), (h, w-1), (h, w+1)]:
            if 0 <= hh <= H-1 and 0 <= ww <= W-1 and marked[hh][ww] == 0:
                heapq.heappush(Q, (d+1, hh, ww))
                marked[hh][ww] = 1
    print(dmax)
    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    H = int(next(tokens))  # type: int
    W = int(next(tokens))  # type: int
    A = [ next(tokens) for _ in range(W) ]  # type: "List[str]"
    solve(H, W, A)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
# coding:utf-8

if __name__=='__main__':
  # input
  H,W = map(int, input().split())
  A = [['.' for i in range(H+2)] for j in range(W+2)]
  B = [(i+1,j+1) for i in range(H) for j in range(W)]
  C =[]
  for i in range(H):
    input_list = input().split()
    for j in range(W):
      A[i+1][j+1]= input_list[j]
      
  # process
  for k in range(H+W):
    for b in B[:]:
      l, m = b
      if A[l][m]=='#':
        B.remove(b)
      elif A[l-1][m]=='#' or A[l][m-1]=='#' or A[l+1][m]=='#' or A[l][m+1]=='#':
        C.append(b)
    for c in C[:]:
      l, m = c
      A[l][m]='#'
      C.remove(c)
    if len(B)==0:
      print(k)
      break;

Submission status: Runtime Error

Solution code:

v = [int(d) for d in input().split()]
f = []

for e in range(v[0]):
    f.append(list(input()))

n = 0
k = []
while True:
    for b in range(v[0]):
        for a in range(v[1]):
            if f[a][b] == '#':
                k.append((a-1,b))
                k.append((a+1,b))
                k.append((a,b-1))
                k.append((a,b+1))
    if k == []:
        break

    for u in k:
        if  u[0] < 0 or u[0] > v[1]-1:
            continue
        elif u[1] < 0 or u[1] > v[0]-1:
            continue
        elif f[u[0]][u[1]] == "#":
            continue

        else:
            f[u[0]][u[1]] = "#"
            
    n += 1
    ee = []
    for qq in f:
        ee.extend(qq)

    if "." not in ee:
        break

print(n)

Submission status: Runtime Error

Solution code:
height, width = map(int, input().split())
A = []
blacks = []
for r_index in range(width):
    row = list(input())
    b = [column_index for column_index, value in enumerate(row) if value == '#']
    A.append(row)
    for i in b:
        blacks.append([r_index,i])

max_length = 0

for h in range(height):
    for w in range(width):
        if A[h][w] == '#':
            continue
        min_length = height + width
        for black in blacks:
            min_length = min(min_length, abs(h - black[0]) + abs(w - black[1]))
        max_length = max(max_length, min_length)

print(max_length)

Submission status: Runtime Error

Solution code:
import sys
import numpy as np

# 黒: #
# 白: .

H, W = input().split()

H = int(H)
W = int(W)

A = np.zeros([H,W])

for i in range(H):
    chars = np.array(list(input()))
    A[i,:] = np.where(chars=='.', 0, 1)

cnt = 0
w_num = np.sum(A == 0)

while w_num != 0:
    cnt += 1
    B = np.zeros([H+2,W+2])
    B[1:H+1,1:W+1] = A

    C = np.zeros([H,W])
    for i in range(W):
        for j in range(H):
            C[i,j] = B[i+1,j+1] + B[i,j+1] + B[i+2,j+1] \
                            + B[i+1,j] + B[i+1,j+2]

    w_num = np.sum(C == 0)
    A = C
    print(A)

print(cnt)

Submission status: Runtime Error

Solution code:
h,w = list(map(int,input().split()))
a = list()
b = [[5000]*w for i in range(0,h)]
now = 0

def find(p,q):
    p1 = min(p+1,h-1)
    p0 = max(p-1,0)
    q1 = min(q+1,w-1)
    q0 = max(q-1,0)
    b[p][q] = 5001
    if b[p1][q] == 5000:
        find(p1,q)
    else:
        b[p][q] = min(b[p][q],b[p1][q]+1)
    if b[p0][q] == 5000:
        find(p0,q)
    else:
        b[p][q] = min(b[p][q],b[p0][q]+1)
    if b[p][q1] == 5000:
        find(p,q1)
    else:
        b[p][q] = min(b[p][q],b[p][q1]+1)
    if b[p][q0] == 5000:
        find(p,q0)
    else:
        b[p][q] = min(b[p][q],b[p][q0]+1)
    b[p][q] = min(b[p][q0],b[p][q1],b[p1][q],b[p0][q])+1


for i in range(0,h):
    a.append(list(input()))
for i in range(0,h):
    for j in range(0,w):
        if a[i][j] == "#":
            b[i][j] = 0

for i in range(0,h):
    for j in range(0,w):
        if b[i][j] == 5000:
            find(i,j)
        now = max(now,b[i][j])
print(now)

Submission status: Runtime Error

Solution code:
H, W = list(map(int, input().split()))

M = {};

for i in range(H):
    M[i] = list(input())

#print(M)

count = 0

flg = True

import copy

f = [[0 for _ in range(W) ] for _ in range(H) ]

temp = copy.deepcopy(M)

while flg:
    count += 1

    for h in range(H):
        for w in range(W):
            if f[h][w] == 0 and temp[h][w] == '#':

                f[h][w] = 1

                for i in range(4):
                    if i == 0 and h != 0:
                        M[h - 1][w] = '#'

                    elif i == 1 and h != H - 1:
                        M[h + 1][w] = '#'

                    elif i == 2 and w != 0:
                        M[h][w - 1] = '#'

                    elif i == 3 and w != W - 1:
                        M[h][w + 1] = '#'

        temp[h] = copy.copy(M[h])

        flg = '.' in W[h]

    # print(count)
    # for h in range(H):
    #     for w in range(W):
    #         print(M[h][w], end="")
    #     print()


print(count)

Submission status: Runtime Error

Solution code:

def main():
    h, w = map(int, input().rstrip().split(' '))
    a = [None] * h
    b = set()
    for i in range(h):
        a[i] = [None] * w
        for j, c in enumerate(input().rstrip()):
            if c == '#':
                a[i][j] = True
                b.add((i, j))
            else:
                a[i][j] = False
    
    max_dist = 0
    for i in range(h):
        for j in range(w):
            if a[i][j]:
                continue
            min_dist = 1000000
            min_dist_black = None
            for black in b:
                p, q = black
                d = abs(p - i) + abs(q - j)
                if d < min_dist:
                    min_dist = d
                    min_dist_black = black
            if max_dist < min_dist:
                max_dist = min_dist
    
    print(min_dist)

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import numpy as np
import copy
import sys
b, c = map(int, input().split())
K = np.zeros((b,c))
for i in range(c):
    s = input()
    for j in range(b):
        if s[j] == "#" :
            K[i,j] =1

count = 0
if np.all(K>0):
    print(0)
else:
    while(1):
        count =count+1
        print(K)
        S = copy.deepcopy(K)
        S1 = np.vstack((S,np.zeros(b).reshape(1,-1)))
        S1 = S1[1:,:]
        print(S1)
        S2 = np.vstack((np.zeros(b).reshape(1,-1),S))
        S2 = S2[0:-1,:]
        print(S2)
        S3 = np.hstack((S,np.zeros(c).reshape(-1,1)))
        S3 = S3[:,1:]
        print(S3)
        S4 = np.hstack((np.zeros(c).reshape(-1,1),S))
        S4 = S4[:,0:-1]
        print(S4)
        K = S+S1+S2+S3+S4
        print(K)
        sys.exit()
        if np.all(K>0):
            break
        

    print(count)

Submission status: Runtime Error

Solution code:
import copy

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

def fib(msLst, i, j):
    if i > 0:
        msLst[i - 1][j] = '#'
    if i < W - 1:
        msLst[i + 1][j] = '#'
    if j > 0:
        msLst[i][j - 1] = '#'
    if j < H - 1:
        msLst[i][j + 1] = '#'

ansCnt = 0
masLst = [['' for i in range(H)] for j in range(W)]
for i in range(W):
    tmp = input()
    for j in range(len(tmp)):
        masLst[i][j] = tmp[j]

loopBoean = True

while loopBoean:
    jloop = True
    tmp = 0
    msLst = copy.deepcopy(masLst)
    for i in range(W):
        for j in range(H):
            if masLst[i][j] == '#':
                fib(msLst, i, j)
            if masLst[i][j] == '.':
                if tmp == 0:
                    tmp = 1
            if msLst[i][j] != '#':
                jloop = False
    masLst = msLst
    if tmp == 1:
        ansCnt += tmp

    if jloop == True:
        loopBoean = False

print(ansCnt)

Submission status: Runtime Error

Solution code:
h,w=map(int,input().split())
a=[list(input()) for i in range(h)]
brack1=[]
brack2=[]
for j in range(h):
    tmp=[i for i, x in enumerate(a[j]) if x == '#']
    [brack1.append(k+1+j+1) for k in tmp]
    [brack2.append(w-k + j + 1) for k in tmp]

brack1=sorted(list(set(brack1)))
brack2=sorted(list(set(brack2)))

brack1.append(h+w+1)
brack2.append(h+w+1)

if len(brack1)>=len(brack2):
    B=len(brack1)
else:
    B=len(brack2)

b=1
c=1
ans=0
for i in range(B):
    if brack1[i]-b-1>ans:
        ans=brack1[i]-b-1
    b=brack1[i]
    if i<len(brack2):
        if brack2[i]-c-1>ans:
            ans=brack2[i]-c-1
    c=brack2[i]

print(ans)

Submission status: Runtime Error

Solution code:
import copy
a = list(map(int, input().split()))
c=[input() for i in range(a[1])]
d=[]
for i in range(a[1]):
  d.append(list(c[i]))
b=[copy.deepcopy(d),copy.deepcopy(d)]
z=1
t=0
f=0
while z==1:
  f=0
  for h in range(a[0]):
    for w in range(a[1]):
      #print(t,h,w,b[t%2])
      if b[t%2][h][w]=='#':
        if h>0 and b[(t)%2][h-1][w] != '#':
          b[(t+1)%2][h-1][w]='#'
          f=1
        if h<a[1]-1 and b[(t)%2][h+1][w] != '#':          
          b[(t+1)%2][h+1][w]='#'
          f=1
        if w>0 and b[(t)%2][h][w-1] != '#':  
          b[(t+1)%2][h][w-1]='#'
          f=1
        if w<a[1]-1 and b[(t)%2][h][w+1] != '#':   
          b[(t+1)%2][h][w+1]='#'
          f=1
  if f==0:
    print(t)
    break
  t=t+1

Submission status: Runtime Error

Solution code:

def input_from_console():
    h, w = map(int, input().split())
    m = list()
    for i in range(h):
        m.append(list(input()))

    return h, w, m


def get_count(h, w, m):
    count = 0
    for i in range(h):
        count += sum([1 for item in m[i] if item == '#'])
    return count


def check(i, j, m, ):
    for ii in [-1, 1]:
        if i + ii < 0 or i + ii > len(m[0]) - 1:
            continue
        if m[i + ii][j] == "#":
            return True

    for jj in [-1, 1]:
        if j + jj < 0 or j + jj > len(m) - 1:
            continue
        if m[i][j + jj] == "#":
            return True
    return False


def main():
    h, w, m = input_from_console()
    total = h * w
    count = 0

    while True:
        flip_list = []
        for i in range(h):
            for j in range(w):
                if m[i][j] != '#' and check(i, j, m):
                    flip_list.append([i,j])
                    # print(flip_list)
        for item in flip_list:
            m[item[0]][item[1]] = '#'
        count += 1
        # print("count", count, get_count(h, w, m), m)
        if get_count(h, w, m) == total:
            print(count)
            break


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import copy 
H, W = map(int, input().split())
lst = []
lst2 = [[0] * W for i in range(H)]
lst3 = copy.deepcopy(lst2)
aaa = True
for h in range(H):
    l = [s for s in input()]
    if '.' in l:
        aaa = False
    lst.append(l)

if aaa:
    print(0)
    exit(0)

def hoge(i, j):
    cnt = 0
    if i > 0 and lst[i - 1][j] != '#' and lst3[i - 1][j] == 0:
        lst[i - 1][j] = '#'
        lst3[i - 1][j] = 1
        cnt += 1
    if i + 1 < W and lst[i + 1][j] != '#' and lst3[i + 1][j]  == 0:
        lst[i + 1][j] = '#'
        lst3[i + 1][j]  = 1
        cnt += 1
    if j > 0 and lst[i][j - 1] != '#' and lst3[i][j - 1] == 0:
        lst[i][j - 1] = '#'
        lst3[i][j - 1] = 1
        cnt += 1
    if j + 1 < H and lst[i][j + 1] != '#' and lst3[i][j + 1] == 0:
        lst[i][j + 1] = '#'
        lst3[i][j + 1] = 1
        cnt += 1
    return cnt


cnt = 0
ret = 0
while True:
    cnt = 0
    lst3 = copy.deepcopy(lst2)
    for j, h in enumerate(lst):
        for i, w in enumerate(h):
            if lst[i][j] == '#' and lst3[i][j] != 1:
                cnt += 1
                a = hoge(i, j)
                cnt += a
    ret += 1
    if cnt >= H * W:
        break

print(ret)

Submission status: Runtime Error

Solution code:
import math
a = list(map(int, input().split()))
b = [[c for c in input()] for l in range(a[0])]
m = [[-1 for c in range(a[1])] for l in range(a[0])]
s = []

def d(i, j, x, y):
    return math.ceil(math.sqrt((x - j) ** 2 + (y - i) ** 2))

for i in range(a[0]):
    for j in range(a[1]):
        if b[i][j] == '#':
            s.append([i, j])
            m[i][j] = 0

for i in range(a[0]):
    for j in range(a[1]):
        if b[i][j] == '.':
            d_min = d(i, j, a[1], a[0])
            for p in s:
                d_min = min(d_min, d(i, j, p[1], p[0]))
            m[i][j] = d_min

return max(sum(m, []))

Submission status: Runtime Error

Solution code:
h,w = list(map(int,input().split()))
a = list()
b = [[5000]*w for i in range(0,h)]
now = 0

def find(p,q):
    p1 = min(p+1,h-1)
    p0 = max(p-1,0)
    q1 = min(q+1,w-1)
    q0 = max(q-1,0)
    b[p][q] = 4999
    if b[p1][q] == 5000:
        find(p1,q)
    else:
        b[p][q] = min(b[p][q],b[p1][q]+1)
    if b[p0][q] == 5000:
        find(p0,q)
    else:
        b[p][q] = min(b[p][q],b[p0][q]+1)
    if b[p][q1] == 5000:
        find(p,q1)
    else:
        b[p][q] = min(b[p][q],b[p][q1]+1)
    if b[p][q0] == 5000:
        find(p,q0)
    else:
        b[p][q] = min(b[p][q],b[p][q0]+1)
    b[p][q] = min(b[p][q0],b[p][q1],b[p1][q],b[p0][q])+1


for i in range(0,h):
    a.append(list(input()))
for i in range(0,h):
    for j in range(0,w):
        if a[i][j] == "#":
            b[i][j] = 0

for i in range(0,h):
    for j in range(0,w):
        if b[i][j] == 5000:
            find(i,j)
        now = max(now,b[i][j])
print(now)

Submission status: Runtime Error

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

q = [(0,0)]
while q != []:
    ny,nx = q.pop(0)
    cand = []
    for py,px in [(ny-1,nx),(ny,nx-1),(ny+1,nx),(ny,nx+1)]:
        if 0<=py<H and 0<=px<W:
            if A[py][px] != "." and A[py][px] != "#":
                cand.append(A[py][px])
            elif A[py][px] == "#":
                A[py][px] = 0
                cand.append(0)
            else:
                q.append((py,px))
    if cand:
        if A[ny][nx] == "." or A[ny][nx] == "#":
            A[ny][nx] = min(cand)+1
        else:
            A[ny][nx] = min(min(cand)+1, A[ny][nx])
m = A[0][0]
for i in range(H):
    for j in range(W):
        m = max(m,A[i][j])
print(m)

Submission status: Runtime Error

Solution code:
def mklist(H,W):
    alllist = []
    for i in range(H):
        for n in range(W):
            alllist.append([i,n])
    return alllist

def black_position(H, W, stonelist):
    bposlist = []
    for i in range(H):
        for n in range(W):
            if stonelist[i][n] == "#":
                bposlist.append([i,n])
    return bposlist

def white_position(H, W, stonelist):
    wposlist = []
    for i in range(H):
        for n in range(W):
            if stonelist[i][n] == ".":
                wposlist.append([i,n])
    return wposlist

def change_black(H, W, bposlist):
    blen = len(bposlist)
    for l in range(blen):
        if bposlist[l][0] - 1 >= 0:
            if bposlist.count([(bposlist[l][0] - 1) , (bposlist[l][1])]) == 0:
                bposlist.append([(bposlist[l][0] - 1) , (bposlist[l][1])])
        if bposlist[l][1] - 1 >= 0:
            if bposlist.count([(bposlist[l][0]) , (bposlist[l][1] - 1)]) == 0:
                bposlist.append([(bposlist[l][0]) , (bposlist[l][1] - 1)])
        if bposlist[l][0] + 1 <= W-1:
            if bposlist.count([(bposlist[l][0] + 1), (bposlist[l][1])]) == 0:
                bposlist.append([(bposlist[l][0] + 1), (bposlist[l][1])])
        if bposlist[l][1] + 1 <= H-1:
            if bposlist.count([(bposlist[l][0]), (bposlist[l][1] + 1)]) == 0:
                bposlist.append([(bposlist[l][0]), (bposlist[l][1] + 1)])
    return bposlist

def check_matrix(alllist, bposlist):
    if len(alllist) == len(bposlist):
        return 1
    else:
        return 0

def ch_all(H, W, alllist,bposlist):
    cnt = 0
    while (check_matrix(alllist, bposlist) == 0):
        bposlist = change_black(H, W, bposlist)
        cnt = cnt + 1
    return cnt

H, W = map(int,input().split())
stonelist = [["0"]*H]*W

for i in range(H):
    stonelist[i] = input()


alist = mklist(H,W)
bpos = black_position(H, W, stonelist)
wpos = white_position(H, W, stonelist)


if wpos == []:
    print(0)
else:
    print(ch_all(H, W, alist,bpos))

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
import sys
from collections.abc import Iterable
from math import *
from itertools import *
from collections import *
from functools import *
from operator import *
try:
    from math import gcd
except Exception:
    from fractions import gcd


def solve(H: int, W: int, A: "List[str]"):
    holes = [[float('inf')] * W for _ in range(H)]
    for i,l in enumerate(A):
        for j, c in enumerate(l):
            if c == '#':
                holes[i][j] = 0
    for i in range(H):
        for j in range(1, W):
            holes[i][j] = min(holes[i][j], holes[i][j-1] + 1)
        for j in range(W - 2, -1, -1):
            holes[i][j] = min(holes[i][j], holes[i][j+1] + 1)

    for j in range(W):
        for i in range(1, H):
            holes[i][j] = min(holes[i][j], holes[i-1][j] + 1)
        for i in range(H - 2, -1, -1):
            holes[i][j] = min(holes[i][j], holes[i+1][j] + 1)

    ret = -float('inf')
    for i in range(H):
        for j in range(W):
            ret = max(ret, holes[i][j])
    return ret


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    H = int(next(tokens))  # type: int
    W = int(next(tokens))  # type: int
    A = [ next(tokens) for _ in range(W) ]  # type: "List[str]"
    result = solve(H, W, A)
    if isinstance(result, Iterable):
        result = '\n'.join([str(v) for v in result])
    print(result)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
from sys import stdin
import copy
sH,sW = stdin.readline().rstrip().split()
H, W = int(sH), int(sW)
A = [[None for w in range(W)] for h in range(H)]
newA = [['.' for w in range(W)] for h in range(H)]
for y in range(H):
    s = stdin.readline().rstrip()
    for x in range(W):
        A[x][y] = s[x]

def debug_print(A):
    check = True
    # print('--------')
    for xx in A:
        for yy in xx:
            if yy == '.':
                check = False
            # print(yy, end='')
        # print('\n')
    return check

status = debug_print(A)
# print(status)

count = 0

def like_dfs(x,y):
    # flag = 0
    newA[x][y] = '#'
    for dx, dy in [[1,0], [0,1], [-1,0], [0,-1]]:
        nx = x + dx
        ny = y + dy
        # print(nx, ny)
        if (0 <= nx and nx < W and 0 <= ny and ny < H and A[nx][ny] == '.'):
            # like_dfs(nx, ny)
            # flag = 1
            newA[nx][ny] = '#'
    # return flag

while(status != True):
    for y in range(H):
        for x in range(W):
            # print("x, y:", x, y)
            if (A[x][y] == '#'):
                like_dfs(x, y)
    count += 1
    status = debug_print(newA)
    # print(status)
    if status == False:
        A = copy.deepcopy(newA)

print(count)

Submission status: Runtime Error

Solution code:
import numpy as np
import sys 


def main():
    H, W = [int(x) for x in sys.stdin.readline().split()]
    board = [[0 for i in range(H)] for j in range(W)]

    """ #は1, .は0 """
    for i in range(H):
        X = sys.stdin.readline()
        for j in range(len(X)):
            if X[j] == "#":
                board[i][j] = 1

    num_board = np.array(board)
    height, width = num_board.shape[:2]
    count = 0
    height_r, width_r = range(height), range(width)
    while (np.sum(num_board) != height*width):
        num_board_ans = np.zeros((height, width))
        for i in height_r:
            for j in width_r:
                if num_board[i, j] == 1:
                    num_board_ans[i, j] = 1
                    a = max(i-1, 0)
                    num_board_ans[a, j] = 1
                    b = max(j-1, 0)
                    num_board_ans[i, b] = 1
                    c = min(i+1, height-1)
                    num_board_ans[c, j] = 1
                    d = min(j+1, width-1)
                    num_board_ans[i, d] = 1
        num_board = num_board_ans
        count += 1

    print(count)


if __name__ == "__main__":
    main()