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:
# 入力が10**5とかになったときに100ms程度早い
import sys
read = sys.stdin.readline


def read_ints():
    return list(map(int, read().split()))


def read_a_int():
    return int(read())


def read_matrix(H):
    '''
    H is number of rows
    '''
    return [list(map(int, read().split())) for _ in range(H)]


def read_map(H, W):
    '''
    H is number of rows
    文字列で与えられた盤面を読み取る用
    '''
    return [read()[:-1] for _ in range(H)]


def read_col(H, n_cols):
    '''
    H is number of rows
    n_cols is number of cols

    A列、B列が与えられるようなとき
    '''
    ret = [[] for _ in range(n_cols)]
    for _ in range(H):
        tmp = list(map(int, read().split()))
        for col in range(n_cols):
            ret[col].append(tmp[col])

    return ret


H, W = read_ints()
A = read_map(H, W)

from itertools import product
from collections import deque


# 開始地点
start = []
for i, a in enumerate(A):
    for j, aa in enumerate(a):
        if aa == '#':
            start.append((i, j))


# 探索の準備
mvx = (1, 0, -1, 0)
mvy = (0, 1, 0, -1)
visited = [[False for _ in range(W)] for _ in range(H)]

n_white = W*H
que = deque([(si, sj, 0) for si, sj in start])

# for si, sj in start:
#     n_white -= 1
#     visited[si][sj] = True

# 幅優先探索
while que:
    y, x, cost = que.popleft()

    for dy, dx in zip(mvy, mvx):
        y_new, x_new = y + dy, x + dx
        # 探索に含めない条件
        if not (-1 < y_new < H) or not (-1 < x_new < W):
            continue
        if visited[y_new][x_new]:
            continue

        # 探索に追加してあげる
        que.append((y_new, x_new, cost + 1))
        visited[y_new][x_new] = True
        # 白マスの数の管理
        n_white -= 1
        if n_white == 0:
            ans = cost+1
            break


print(ans)

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 check_filled(h, w, m):
    count = 0
    for i in range(h):
        if all(m[i]):
            print(m[i])
            count += 1
    if count == h:
        return True
    return False



def check(h, w, m):
    n = m.copy()

    for i in range(h):
        # left
        # print(i)
        n[i] = [n[i][j] + m[i][j - 1] for j in range(1, w)] + [n[i][w - 1]]
        # print(n)
        # right
        n[i] = [n[i][0]] + [n[i][j + 1] + m[i][j] for j in range(w - 1)]
        if i >= 1:  # up
            n[i] = [n[i][j] + m[i - 1][j] for j in range(w)]
        # print(n)
        if i < w - 1:  # down
            n[i] = [n[i][j] + m[i + 1][j] for j in range(w)]
        # print(n)
    return n


def main():
    h, w, m = input_from_console()
    total = h * w
    count = 0
    mat = [0] * h
    for i in range(h):
        mat[i] = [0 if item == '.' else 1 for item in m[i]]

    while True:
        print(h, w, mat)
        mat = check(h, w, mat)
        count += 1
        if check_filled(h, w, mat):
            print("count", count, mat)
            break


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import numpy as np

def solve():
    H,W=map(int,input().split(' '))
    max_value = H+W
    values =[]
    for i in range(H):
      values.append([0 if i == '#' else max_value for i in list(input())])
    values = np.array(values)

    for x in range(W-1):
        values[:,x+1] = np.minimum(values[:,x]+1,values[:,x+1])
    for x in range(W-1,0,-1):
        values[:,x] = np.minimum(values[:,x+1]+1,values[:,x])
    for x in range(H-1):
        values[x+1,:] = np.minimum(values[x,:]+1,values[x+1,:])
    for x in range(H-1,0,-1):
        values[x,:] = np.minimum(values[x+1,:]+1,values[x,:])

    print(np.max(values),)
solve()

Submission status: Runtime Error

Solution code:
h, w = map(int, input().split())
rb = [['#'] * (w + 2)]
a = rb + [list('#' + input() + '#') for _ in range(h)] + rb
p = [(i, j) for i in range(1, h + 1) for j in range(1, w + 1) if a[i][j] == '#']
d = (-1, 0), (1, 0), (0, -1), (0, 1)
r = -1
while p:
    r += 1
    s = []
    for i, j in p:
    for di, dj in d:
            di += i
            dj += j
            if a[di][dj] == '.':
                a[di][dj] = '#'
                s.append((di, dj))
    p = s
print(r)

Submission status: Runtime Error

Solution code:
h, w = map(int, input().split())
rb = ['#'] * (w + 2)
a = [rb + [['#'] + list(input()) + ['#'] for _ in range(h)] + rb]
p = [(i, j) for i in range(1, h + 1) for j in range(1, w + 1) if a[i][j] == '#']
d = (-1, 0), (1, 0), (0, -1), (0, 1)
r = -1
while p:
    r += 1
    s = []
    for i, j in p:
        for di, dj in d:
            di += i
            dj += j
            if a[di][dj] == '.':
                a[di][dj] = '#'
                s.append((di, dj))
    p = s
print(r)

Submission status: Runtime Error

Solution code:
h, w = map(int, input().split())
rb = ['#'] * (w + 2)]
a = [rb + [['#'] + list(input()) + ['#'] for _ in range(h)] + rb]
p = [(i, j) for i in range(1, h + 1) for j in range(1, w + 1) if a[i][j] == '#']
d = (-1, 0), (1, 0), (0, -1), (0, 1)
r = -1
while p:
    r += 1
    s = []
    for i, j in p:
        for di, dj in d:
            di += i
            dj += j
            if a[di][dj] == '.':
                a[di][dj] = '#'
                s.append((di, dj))
    p = s
print(r)

Submission status: Runtime Error

Solution code:
H, W = tuple(map(int, input().split()))
func = (lambda x: 0 if x == "#" else -1)
func_in = (lambda h, w: 0 <= h < H and 0 <= w < W)
P = [[func(i) for i in input()] for i in range(H)]

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

queue = [[q // W, q % W, 0] for q in queue_set]
queue_set |= zeros
idx = 0
while len(queue) > idx:
    h, w, cnt = queue[idx]
    idx += 1
    cnt += 1
    P[h][w] = cnt
    a = 0
    for dh, dw in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
        if func_in(h+dh, w+dw) and (h+dh)*W+w+dw not in queue_set:
            queue += [[h + dh, w + dw, cnt]]
            queue_set.add((h+dh)*W+w+dw)
print(cnt)

Submission status: Runtime Error

Solution code:
    H,W=map(int,input().split())
    S = []
    for _ in range(H):
        S.append(input())
     
    li1=[]
     
    for i in range(H):
        for j in range(W):
            if S[i][j]=="#":
                li1.append([i,j])
     
    e=H*W
    f=0
     
    for i in range(H):
        for j in range(W):
            if S[i][j]==".":
                e=H*W
                for k in li1:
                    ca=abs(i-k[0])+abs(j-k[1])
                    e=min(e,ca)
                f=max(f,e)
     
    print(f)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(H, W, A):
    cost = [[-1] * W for _ in range(H)]
    bq = []
    for i in range(H):
        for j in range(W):
            if A[i][j] == "#":
                heapq.heappush(bq, (0, (i, j)))
                cost[i][j] = 0

    ans = 0
    while bq:
        c, (i, j) = heapq.heappop(bq)
        if i > 0 and cost[i-1][j] == -1:
            cost[i-1][j] = c + 1
            heapq.heappush(bq, (c+1, (i-1, j)))
            ans = max(ans, c + 1)

        if i < W-1 and cost[i+1][j] == -1:
            cost[i+1][j] = c + 1
            heapq.heappush(bq, (c+1, (i+1, j)))
            ans = max(ans, c + 1)

        if j > 0 and cost[i][j-1] == -1:
            cost[i][j-1] = c + 1
            heapq.heappush(bq, (c+1, (i, j-1)))
            ans = max(ans, c + 1)

        if j < H-1 and cost[i][j+1] == -1:
            cost[i][j+1] = c + 1
            heapq.heappush(bq, (c+1, (i, j+1)))
            ans = max(ans, c + 1)

    # print(cost)
    return ans


def main():
    H, W = read_int_n()
    A = [read_str() for _ in range(H)]
    print(slv(H, W, A))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
H, W = map(int, input().split())
a = []
INF = 10**9
for i in range(H):
    a.append(input())

# 黒マスの位置を記録
black_pos = []
for i in range(H):
    for j in range(W):
        if a[i][j] == "#":
            black_pos.append([i, j])

# 白マスごとに最近傍の黒マスまでの距離を計算
dist_list = []
for i in range(H):
    for j in range(W):
        if a[i][j] == "#":
            continue
        min_dist = INF
        for pos in black_pos:
            dist = abs(pos[0]-i) + abs(pos[1]-j)
            if dist < min_dist:
                min_dist = dist
        dist_list.append(min_dist)

print(max(dist_list))

Submission status: Runtime Error

Solution code:
# import time
import numpy as np
# start = time.time()

h, w = map(int, input().split())
a = []
L = {}
cl = [set([]) for i in range(2000)]
for i in range(h):
    a.append(input())
    for j in range(w):
        if a[i][j] == '#':
            L[(i, j)] = 0
            cl[0].add((i, j))
# elapsed_time = time.time() - start
# print("elapsed_time1:{0}".format(elapsed_time) + "[sec]")

cnt = 1
sl = [(-1, 0), (0, -1), (1, 0), (0, 1)]
while len(L) < h*w:
    for c in cl[cnt - 1]:
        i = c[0]
        j = c[1]
        for s in sl:
            p = (i + s[0], j + s[1])
            if p in L or p[0] >= h or p[1] >= w or p[0] < 0 or p[1] < 0:
                continue
            L[p] = cnt
            cl[cnt].add(p)
    cnt += 1

print(cnt - 1)
# elapsed_time = time.time() - start
# print("elapsed_time2:{0}".format(elapsed_time) + "[sec]")

Submission status: Runtime Error

Solution code:
import numpy as np
import math

h, w = map(int, input().split())
A=[]

for i in range(0,h):
    A.append(list(str(x) for x in input()))

A = np.array(A)

B1 = np.where(A == "#")
B1 = np.array([B1[0], B1[1]]).T

B2 = np.where(A == ".")
B2 = np.array([B2[0], B2[1]]).T

B3=B2[B2[:,0]==0]
B3=np.append(B3,B2[B2[:,0]==h-1],axis=0)
B3=np.append(B3,B2[B2[:,1]==0],axis=0)
B3=np.append(B3,B2[B2[:,1]==w-1],axis=0
B3 = list(map(list, set(map(tuple, B3))))
             
C1=np.zeros(len(B1))
C2=np.zeros(len(B3))

for i in range(0,len(B1)):
    temp=[]
    for j in range(0,i):
        temp.append(math.ceil(sum(np.abs(B1[i]-B1[j]))/2))
        C1[i]=min(temp)
        
for i in range(0, len(B3)):
    temp=[]
    for j in range(0,len(B1)):
        temp.append(sum(np.abs(B3[i]-B1[j])))
        C2[i]=min(temp)
        
C3= np.insert(C1,0,C2)
             
print(int(max(C3)))

Submission status: Runtime Error

Solution code:
from collections import deque


def inside(x, l, r):
    return l <= x < r


H, W = map(int, input().split())
A = [list(input()) for i in range(H)]
qu = deque()

rest = H * W
for i in range(H):
    for j in range(W):
        if A[i][j] == '#':
            rest -= 1
            qu.put((i, j))

ans = 0
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
while True:
    if rest == 0:
        break
    ans += 1
    qu2 = deque()
    while qu:
        i0, j0 = qu.get()
        for k in range(4):
            ni = i0 + dx[k]
            nj = j0 + dy[k]
            if not (inside(ni, 0, H) and inside(nj, 0, W)):
                continue
            if A[ni][nj] == '.':
                A[ni][nj] = '#'
                rest -= 1
                qu2.put((ni, nj))
    qu = qu2
print(ans)

Submission status: Runtime Error

Solution code:
X = [int(i) for i in input().split()]
queue = [(i,j) for i in range(X[0]) for j,s in enumerate(input()) if s=="#"]
end = []
# for n in range(0,100):
#     tmp = []
#     end += queue
#     for q in queue:
#         i,j = q[0],q[1]
#         up = max(0, i-1)
#         down = min(i+1, X[0]-1)
#         left = max(0, j-1)
#         right = min(j+1, X[1]-1)
#         tmp += [t for t in [(up,j),(down,j),(i,left),(i,right)] if t not in end]
#     queue = list(set(tmp))
#     if len(queue) == 0:
#         break
print(n)

Submission status: Runtime Error

Solution code:
H,W = map(int,input().split()) 
A = [[0]*H for _ in range(W)]
M = 0
queue = []
for i in range(H):
  s = input()
  for j in range(W):
    if s[j]== '#':
      queue.append([i,j,0])
      A[i][j] = '#'
while queue:
  i,j,cost = queue.pop(0)
  M=max(M,cost)
  if i+1 < H and A[i+1][j] != '#':
    queue.append([i+1,j,cost+1])
    A[i+1][j] = '#'
  if i-1 >= 0 and A[i-1][j] != '#':
    queue.append([i-1,j,cost+1])
    A[i-1][j] = '#'
  if j+1 < W and A[i][j+1] != '#':
    queue.append([i,j+1,cost+1])
    A[i][j+1] = '#'
  if j-1 >= 0 and A[i][j-1] != '#':
    queue.append([i,j-1,cost+1])
    A[i][j-1] = '#'
print(M)

Submission status: Runtime Error

Solution code:
from itertools import product
from collections import deque

H, W = map(int, input().split())
A = []
checked = []
black = []
INF = 10**9
for i in range(H):
    tmp = input()
    A.append(tmp)
    checked.append([0 if tmp[j] == '#' else INF for j in range(W)])
    black += [((i, j), 0) for j in range(W) if checked[-1][j] == 0]
black = deque(black)
ans = 0
while black:
    (i, j), d = black.popleft()
    ans = max(ans, d)
    if i > 0:
        checked[i-1][j] = min(checked[i-1][j], d+1)
        black.append((i-1, j), checked[i-1][j])
    if i < H-1:
        checked[i+1][j] = min(checked[i+1][j], d+1)
        black.append((i+1, j), checked[i+1][j])
    if j > 0:
        checked[i][j-1] = min(checked[i][j-1], d+1)
        black.append((i, j-1), checked[i][j-1])
    if j < W-1:
        checked[i][j+1] = min(checked[i][j+1], d+1)
        black.append((i, j+1), checked[i][j+1])
print(ans)

Submission status: Runtime Error

Solution code:
H,W = map(int,input().split()) 
A = [0]*H
M = 0
queue = []
for i in range(H):
  A[i] = input()
  for j in range(W):
    if A[i][j] == '#':
      queue.append([i,j,0])
while queue:
  i,j,cost = queue.pop(0)
  if i+1 < H and A[i+1][j] != '#':
    queue.append([i+1,j,cost+1])
    A[i+1][j] = '#'
  if i-1 >= 0 and A[i-1][j] != '#':
    queue.append([i-1,j,cost+1])
    A[i-1][j] = '#'
  if j+1 < W and A[i][j+1] != '#':
    queue.append([i,j+1,cost+1])
    A[i][j+1] = '#'
  if j-1 >= 0 and A[i][j-1] != '#':
    queue.append([i,j-1,cost+1])
    A[i][j-1] = '#'
print(M)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
import sys
from math import *
from itertools import *
from collections import *
from functools import *
from operator import *


def solve(H: int, W: int, A: "List[str]"):
    queue = deque()

    rem = H * W
    for i in range(H):
        for j in range(W):
            if A[i][j] == '#':
                queue.append((i, j, 0))
    
    ret = 0
    visited = [[False] * W for _ in range(H)]
    while 0 < len(queue):
        i, j, n = queue.popleft()
        if visited[i][j]:
            continue
        visited[i][j] = True
        ret = max(ret, n)

        rem -= 1
        #if rem == 0:
        #    break

        for dx, dy in zip([0, 1, 0, -1], [1, 0, -1, 0]):
            nx = j + dx
            ny = i + dy
            if (0 <= nx < W) and (0 <= ny < H):
                queue.append((ny, nx, n + 1))
        #if 0 < j:
        #    queue.append((i, j - 1, n + 1))
        #if j < W - 1:
        #    queue.append((i, j + 1, n + 1))
        #if 0 < i:
        #    queue.append((i - 1, j, n + 1))
        #if i < H - 1:
        #    queue.append((i + 1, j, n + 1))
    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)
    print(result)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import itertools
import numpy as np
h, w = map(int, input().split())

blacks = set()
for x in range(h):
    for y, masu in enumerate(input()):
        if masu == '#':
            blacks.add((x, y))

mat = np.zeros(shape=(h, w))
for b_x, b_y in blacks:
    mat[b_x][b_y] = 1

for cnt in itertools.count(1):
    additions = list()
    for b_x, b_y in blacks:
        if b_x > 0 and mat[b_x - 1][b_y] == 0:
            additions.append((b_x - 1, b_y))
            mat[b_x - 1][b_y] = 1
        if b_x < w - 1 and mat[b_x + 1][b_y] == 0:
            additions.append((b_x + 1, b_y))
            mat[b_x + 1][b_y] = 1
        if b_y > 0 and mat[b_x][b_y - 1] == 0:
            additions.append((b_x, b_y - 1))
            mat[b_x][b_y - 1] = 1
        if b_y < h - 1 and mat[b_x][b_y + 1] == 0:
            additions.append((b_x, b_y + 1))
            mat[b_x][b_y + 1] = 1
    blacks = blacks.union(additions)
    if len(blacks) == h * w:
        break

print(cnt)

Submission status: Runtime Error

Solution code:
import numpy as np
import copy
H,W = input().split()
H = int(H)
W = int(W)
s = [input() for i in range(H)]
text = s[1]
HW = np.zeros([H,W])
for i in range(H):
  for j in range(W):
    if s[i][j] == '.': #白
      HW[i,j] = 0
    else:
      HW[i,j] = 1 #黒

k = HW.sum()
HW_alpha = np.zeros([H+2,W+2])
HW_alpha[1:-1,1:-1]=copy.deepcopy(HW)
num = 0
while int(k) != H*W:
  
  HW_alpha[0:-2,1:-1]=HW_alpha[0:-2,1:-1]+np.array([HW==1])*1
  HW_alpha[2:,1:-1]=HW_alpha[2:,1:-1]+np.array([HW==1])*1
  HW_alpha[1:-1,0:-2]=HW_alpha[1:-1,0:-2]+np.array([HW==1])*1
  HW_alpha[1:-1,2:]=HW_alpha[1:-1,2:]+np.array([HW==1])*1
  HW_alpha=HW_alpha!=0
  HW=copy.deepcopy(HW_alpha[1:-1,1:-1])
  num = num +1
  k = HW.sum()

print(num)

Submission status: Runtime Error

Solution code:
h, w = map(int, input().split())
a = []
for _ in range(h):
   tmp = list(input().split())
   a.append(tmp)

for i, item in enumerate(a):
   a[i] = list(item[0])

visited = [[0 for _ in range(len(a[0]))] for _ in range(len(a))]
change = [[0 for _ in range(len(a[0]))] for _ in range(len(a))]

rest = h * w

for line in a:
    for e in line:
        if (e == '#'): rest -= 1


def isWhite(a):
   items = []
   for i in range(len(a)):
       items.extend(a[i])
   print(items)
   if "." in items:
       return True
   return False

cnt = 0
while rest:
   flg = False
   for i in range(len(a)):
       for j in range(len(a[0])):
           if a[i][j] == "#":
               visited[i][j] = 1
               if i - 1 >= 0:
                   if a[i - 1][j] != "#":
                       change[i-1][j] = 1
               if i + 1 < len(a):
                   if a[i + 1][j] != "#":
                       change[i+1][j] = 1
               if j - 1 >= 0:
                   if a[i][j - 1] != "#":
                       change[i][j-1] = 1
               if j + 1 < len(a):
                   if a[i][j + 1] != "#":
                       change[i][j+1] = 1
               if not flg:
                   cnt += 1
               flg = True
   for i in range(len(a)):
       for j in range(len(a[0])):
           if change[i][j] == 1:
               change[i][j] = 0
               a[i][j] = "#"
               rest -= 1

print(cnt)

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]"):
    queue = deque()

    rem = H * W
    for i in range(H):
        for j in range(W):
            if A[i][j] == '#':
                queue.append((i, j, 0))
    
    ret = 0
    visited = [[False] * W for _ in range(H)]
    while 0 < len(queue):
        i, j, n = queue.popleft()
        if visited[i][j]:
            continue
        visited[i][j] = True
        ret = max(ret, n)

        rem -= 1
        #if rem == 0:
        #    break

        for dx, dy in zip([0, 1, 0, -1], [1, 0, -1, 0]):
            nx = j + dx
            ny = i + dy
            if (0 <= nx < W) and (0 <= ny < H):
                queue.append((ny, nx, n + 1))
        #if 0 < j:
        #    queue.append((i, j - 1, n + 1))
        #if j < W - 1:
        #    queue.append((i, j + 1, n + 1))
        #if 0 < i:
        #    queue.append((i - 1, j, n + 1))
        #if i < H - 1:
        #    queue.append((i + 1, j, n + 1))
    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:
# -*- coding: utf-8 -*-
import itertools
import numpy as np
h, w = map(int, input().split())

blacks = set()
for x in range(h):
    for y, masu in enumerate(input()):
        if masu == '#':
            blacks.add((x, y))

mat = np.zeros(shape=(w, h))
for b_x, b_y in blacks:
    mat[b_x][b_y] = 1

for cnt in itertools.count(1):
    additions = list()
    for b_x, b_y in blacks:
        if b_x > 0 and mat[b_x - 1][b_y] == 0:
            additions.append((b_x - 1, b_y))
            mat[b_x - 1][b_y] = 1
        if b_x < h - 1 and mat[b_x + 1][b_y] == 0:
            additions.append((b_x + 1, b_y))
            mat[b_x + 1][b_y] = 1
        if b_y > 0 and mat[b_x][b_y - 1] == 0:
            additions.append((b_x, b_y - 1))
            mat[b_x][b_y - 1] = 1
        if b_y < w - 1 and mat[b_x][b_y + 1] == 0:
            additions.append((b_x, b_y + 1))
            mat[b_x][b_y + 1] = 1
    blacks = blacks.union(additions)
    if len(blacks) == h * w:
        break

print(cnt)

Submission status: Runtime Error

Solution code:
H,W = map(int,input().split())
A = [[[j,i] for i,s in enumerate(input()) if s=='#'] for j in range(H)]
A = [A[i][j] for i in range(len(a)) for j in range(len(A[i])) if not i==[]]
d = 0
for i in range(H):
    for j in range(W):
        n = min([abs(i-p[0])+abs(j-p[1]) for p in A])
        if(d<n):
            d = n
print(d)

Submission status: Runtime Error

Solution code:
H,W = map(int,input().split())
A = [[[j,i] for i,s in enumerate(input()) if s=='#'] for j in range(H)]
A = [A[i][j] for i in range(len(a)) for j in range(len(A[i])) if not i==[]]
d = 0
black = []
for i in range(H):
    for j in range(W):
        n = min([abs(i-p[0])+abs(j-p[1]) for p in A])
        if(d<n):
            d = n
print(d)

Submission status: Runtime Error

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

def solve(H: int, W: int, black):
    Q = queue.Queue()
    marked = [[0] * W for h in range(H)]
    qlen = 0
    for h, w in black:
        Q.put((h, w))
        qlen += 1
        marked[h][w] = 1
    
    count = 0
    while not Q.empty():
        flag = False
        for _ in range(qlen):
            h, w = Q.get()
            qlen -= 1
            for hh, ww in [(h-1, w), (h+1, w), (h, w-1), (h, w+1)]:
                if not marked[hh][ww] and 0 <= hh <= H-1 and 0 <= ww <= W-1:
                    flag = True
                    Q.put((hh, ww))
                    qlen += 1
                    marked[hh][ww] = 1
        if flag:
            count += 1
    print(count)
    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
    black = []
    for h in range(H):
        line = next(tokens)
        for w, c in enumerate(line):
            if c == '#':
                black.append((h, w))
    solve(H, W, black)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:

import numpy as np
import sys
input = sys.stdin.readline

h,w = map(int, input().split())

A_array = np.array(
    [[1 if s == "#" else 0 for s in input()[:-1]] for i in range(h)])
ans=0
a=[]
b=[0]
c=[]
d=[0]
for i in range(h-1):
    a.append(i+1)
    b.append(i)
a.append(h-1)
for i in range(w-1):
    c.append(i+1)
    d.append(i)
c.append(w-1)


while np.min(A_array) == 0:
    l=col_swap = A_array[:, d]
    r=col_swap = A_array[:, c]
    u=row_swap = A_array[a, :]
    d=row_swap = A_array[b, :]

    A_array = A_array + l + r + u + d
    ans += 1

print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np

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

x = []
for h in range(H):
    line = list(input())
    for _ in line:
        for value in _:
            x.append(value)
x = np.array(x)
x = x.reshape(num_i, num_j)

count = 0
boolean = True
while (boolean):
    count += 1
    i_arr = []
    j_arr = []
    for i in range(num_i):
        for j in range(num_j):
            if (x[i][j] == "#"):
                i_arr.append(i)
                j_arr.append(j)
    for i, j in zip(i_arr, j_arr):
        if (i == 0) & (j == 0):
            x[1][0] = "#"
            x[0][1] = "#"
        elif (i == num_i - 1) & (j == num_j - 1):
            x[i - 1][j] = "#"
            x[i][j - 1] = "#"
        elif (i == num_i - 1) & (j == 0):
            x[i - 1][0] = "#"
            x[i][1] = "#"
        elif (i == 0) & (j == num_j - 1):
            x[1][j] = "#"
            x[0][j - 1] = "#"
        elif (i == 0):
            x[1][j] = "#"
            x[0][j - 1] = "#"
            x[0][j + 1] = "#"
        elif (j == 0):
            x[i - 1][0] = "#"
            x[i + 1][0] = "#"
            x[i][1] = "#"
        elif (i == num_i - 1):
            x[i - 1][j] = "#"
            x[i][j + 1] = "#"
            x[i][j - 1] = "#"
        elif (j == num_j - 1):
            x[i - 1][j] = "#"
            x[i + 1][j] = "#"
            x[i][j - 1] = "#"
        else:
            x[i - 1][j] = "#"
            x[i + 1][j] = "#"
            x[i][j - 1] = "#"
            x[i][j + 1] = "#"
    if len(set(list(x.flatten()))) == 1:
        boolean = False
    else:
        boolean = True

print(count)

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]"):
    queue = deque()

    rem = H * W
    for i,l in enumerate(A):
        for j, c in enumerate(l):
            if c == '#':
                queue.append((i, j, 0))
    
    ret = 0
    visited = [[False] * W for _ in range(H)]
    while queue:
        i, j, n = queue.popleft()
        if visited[i][j]:
            continue
        visited[i][j] = True
        ret = max(ret, n)

        rem -= 1
        if rem == 0:
            break

        if 0 < j:
            queue.append((i, j - 1, n + 1))
        if j < W - 1:
            queue.append((i, j + 1, n + 1))
        if 0 < i:
            queue.append((i - 1, j, n + 1))
        if i < H - 1:
            queue.append((i + 1, j, n + 1))
    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:
h,w=map(int,input().split())
li=[input() for i in range(h)]





black=list()
bli=[[0 for j in range(h)] for i in range(w)]
count=0


for i in range(h):
    for j  in range(w):
        if li[i][j]=="#":
            black.append([i,j])
            bli[i][j]=1

def check(li):
    s=0
    for i in li:
        for j in i:
            if j==0:
                return True
            
    return False
        
        
while check(bli):
    count+=1
    tmp=[]
    
    for i in black:
        if i[0]-1>-1:
            bli[i[0]-1][i[1]]=2
            tmp.append([i[0]-1,i[1]])
        if i[0]+1<h:
            bli[i[0]+1][i[1]]=2
            tmp.append([i[0]+1,i[1]])

        if i[1]+1<w:
            bli[i[0]][i[1]+1]=2
            tmp.append([i[0],i[1]+1])

        if i[1]-1>-1:
            bli[i[0]][i[1]-1]=2
            tmp.append([i[0],i[1]-1])

    black=tmp[:]
  
 
    
print(count)