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:
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
    #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
    rt=[0]
    for i in ls:rt+=[rt[-1]+i]
    return rt
def bit_combination(n,base=2):
    rt=[]
    for tb in range(base**n):s=[tb//(base**bt)%base for bt in range(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
read=sys.stdin.buffer.read
readline=sys.stdin.buffer.readline
input=lambda: sys.stdin.readline().rstrip()

class Tree:
    def __init__(self,inp_size=None,ls=None,init=True,index=1):
        self.LCA_init_stat=False
        self.ETtable=[]
        if init:
            if ls==None:
                self.stdin(inp_size,index=index)
            else:
                self.node_size=len(ls)+1
                self.edges,_=GI(self.node_size,self.node_size-1,ls,index=index)
        return
 
    def stdin(self,inp_size=None,index=1):
        if inp_size==None:
            self.node_size=int(input())
        else:
            self.node_size=inp_size
        self.edges,_=GI(self.node_size,self.node_size-1,index=index)
        return
    
    def listin(self,ls,index=0):
        self.node_size=len(ls)+1
        self.edges,_=GI(self.node_size,self.node_size-1,ls,index=index)
        return
 
    def dfs(self,x,func=lambda pr,prv,nx,dist:prv+dist,root_v=0):
        q=deque([x])
        v=[None]*self.node_size
        v[x]=root_v
        while q:
            c=q.pop()
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=func(c,v[c],nb,d)
        return v
 
    def bfs(self,x,func=lambda pr,prv,nx,dist:prv+dist,root_v=0):
        q=deque([x])
        v=[None]*self.node_size
        v[x]=root_v
        while q:
            c=q.popleft()
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=func(c,v[c],nb,d)
        return v
 
    def parent(self,x):
        return self.dfs(0,func=lambda pr,prv,nx,dist:pr,root_v=-1)
 
    def topological_sort(self,x):  # return topological sort of the tree
        tps=[]
        q=deque([x])
        v=[None]*self.node_size
        v[x]=0
        while q:
            c=q.popleft()
            tps.append(c)
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=0
        return tps
 
    def EulerTour(self,x):
        q=deque()
        q.append(x)
        self.depth=[None]*self.node_size
        self.depth[x]=0
        self.ETtable=[]
        self.ETdepth=[]
        self.ETin=[-1]*self.node_size
        self.ETout=[-1]*self.node_size
        cnt=0
        while q:
            c=q.pop()
            if c<0:
                ce=~c
            else:
                ce=c
                for nb,d in self.edges[ce]:
                    if self.depth[nb]==None:
                        q.append(~ce)
                        q.append(nb)
                        self.depth[nb]=self.depth[ce]+1
            self.ETtable.append(ce)
            self.ETdepth.append(self.depth[ce])
            if self.ETin[ce]==-1:
                self.ETin[ce]=cnt
            else:
                self.ETout[ce]=cnt
            cnt+=1
        return
    
    def LCA_init(self,root):
        self.EulerTour(root)
        self.st=SparseTable(self.ETdepth,init_func=min,init_idl=inf)
        #self.st=SegTree(self.node_size*2-1,self.ETdepth,function=min,ide=inf)
        self.LCA_init_stat=True
        return
    
    def LCA(self,root,x,y):
        if self.LCA_init_stat==False:
            self.LCA_init(root)
        xin,xout=self.ETin[x],self.ETout[x]
        yin,yout=self.ETin[y],self.ETout[y]
        a=min(xin,yin)
        b=max(xout,yout,xin,yin)
        id_of_min_dep_in_et=self.st.query_id(a,b+1)
        return self.ETtable[id_of_min_dep_in_et]
 
    def __str__(self):
        return  str(self.edges)
 
    def show(self):
        if all([all([d==1 for nd,d in e]) for e in self.edges]):
            print( [[nd for nd,d in e] for e in self.edges] )
        else:
            print(self)

class SparseTable: # O(N log N) for init, O(1) for query(l,r)
    def __init__(self,ls,init_func=min,init_idl=float('inf')):
        self.func=init_func
        self.idl=init_idl
        self.size=len(ls)
        self.N0=self.size.bit_length()
        self.table=[ls[:]]
        self.index=[list(range(self.size))]
        self.lg=[0]*(self.size+1)
        
        for i in range(2,self.size+1):
            self.lg[i]=self.lg[i>>1]+1
 
        for i in range(self.N0):
            tmp=[self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) for j in range(self.size)]
            tmp_id=[self.index[i][j] if self.table[i][j]==self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) else self.index[i][min(j+(1<<i),self.size-1)] for j in range(self.size)]
            self.table+=[tmp]
            self.index+=[tmp_id]
    
    # return func of [l,r)
    def query(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        return self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))])
    
    # return index of which val[i] = func of v among [l,r)
    def query_id(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        a,b=self.index[N][l],self.index[N][max(0,r-(1<<N))]
        if self.table[0][a]==self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))]):
            b=a
        return b
    
    # return boundary index of r such that func({table[i]} =< x , i in [pos,r]
    def right_bound(self,pos,x):
        k=(self.size-pos).bit_length()
        for j in range(k)[::-1]:
            nx=pos+(1<<j)
            if nx<n and self.query(pos,nx+1)<=x:
                pos+=(1<<j)
        return pos
    
    # return boundary index of l such that func({table[i]} =< x , i in [l,pos]
    def left_bound(self,pos,x):
        k=pos.bit_length()
        for j in range(k)[::-1]:
            nx=pos-(1<<j)
            if 0<=nx and self.query(nx,pos+1)<=x:
                pos-=(1<<j)
        return pos
 
    def __str__(self):
        return str(self.table[0])
 
    def print(self):
        for i in self.table:
            print(*i)


show_flg=False
show_flg=True
ans=0


class Graph:
    def __init__(self,inp_node_size=None,inp_edge_size=None,ls=None,init=True,Directed=False,index=1):
        if init:
            self.IsGrid=False
            if ls==None:
                self.stdin(inp_node_size,inp_edge_size,Directed=Directed,index=index)
            else:
                self.listin(ls,Directed=Directed,index=index)
        else:
            self.edges=[]
        return

    def stdin(self,inp_node_size=None,inp_edge_size=None,Directed=False,index=1):
        if (inp_node_size,inp_edge_size)==(None,None):
            self.node_size,self.edge_size=LI()
            self.edges,_=GI(self.node_size,self.edge_size,Directed=Directed,index=index)
        else:
            self.node_size,self.edge_size=inp_node_size,inp_edge_size
            self.edges,_=GI(self.node_size,self.edge_size,Directed=Directed,index=index)
        return

    def listin(self,inp_node_size,ls,Directed=False,index=0):
        self.node_size,self.edge_size=inp_node_size,len(ls)
        self.edges,_=GI(self.node_size,self.edge_size,ls,Directed=Directed,index=index)
        return

    def edgein(self,inp_edge,index=0):
        self.node_size,self.edge_size=len(inp_edge),0
        self.edges=[0]*self.node_size
        for i in range(self.node_size):
            self.edges[i]=inp_edge[i][:]
        return
    
    def _gridin(self,h,w):
        self.node_size,self.edge_size=h*w,0
        self.edges=[0]*self.node_size
        self.edges=GGI(h,w)
        return

    def gridin(self,h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0}):
        #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
        self.mp,found=[],{}
        if search==None:
            search=[]
        self.node_size,self.edge_size,self.grid_h,self.grid_w=h*w,0,h,w
        self.edges=[[] for i in range(self.node_size)]
        self.IsGrid=True
        for i in range(h):
            s=input()
            for char in search:
                if char in s:
                    found[char]=(i*w+s.index(char))
                    mp_def[char]=mp_def[replacement_of_found]
            self.mp+=[mp_def[j] for j in s]
        for node in range(self.node_size):
            for dd in [1,-1,w,-w]:
                nx=node+dd
                if 0<=nx<self.node_size:
                    if self.mp[nx]==0 and (nx//w==node//w or nx%w==node%w):
                        self.edges[node]+=[(nx,1)]
        return self.mp,found

    def dfs(self,x,func=lambda pr,prv,nx,dist:prv+dist,root_v=0):
        q=deque([x])
        v=[None]*self.node_size
        v[x]=root_v
        while q:
            c=q.pop()
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=func(c,v[c],nb,d)
        return v

    def bfs(self,x,func=lambda pr,prv,nx,dist:prv+dist,root_v=0):
        
        q=deque()
        v=[None]*self.node_size
        for i in range(self.node_size):
          if self.mp[i]==1:
            q.append(i)
            v[i]=root_v
        while q:
            c=q.popleft()
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=v[c]+1
        return v

    def parent(self,x):
        return self.bfs(0,func=lambda pr,prv,nx,dist:pr,root_v=-1)

    def topological_sort(self,x):  # return topological sort of the tree
        tps=[]
        q=deque([x])
        v=[None]*self.node_size
        v[x]=0
        while q:
            c=q.popleft()
            tps.append(c)
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=0
        return tps

    def dijkstra(self,st):
        # edge=[[(v_to,dist_to_v),...],[],...]
        # initialize: def: d=dist(st,i), prev=[previous vertex in minimum path], q[]
        d=[(0 if st==i else inf) for i in range(self.node_size)]
        prev=[0]*self.node_size
        q=[(j,i) for i,j in enumerate(d)]
        heapify(q)
        v=[False]*self.node_size
        # calc
        while q:
            dist,cur=heappop(q)
            if v[cur]:
                continue
            v[cur]=True
            for dst,dist in self.edges[cur]:
                alt=d[cur]+dist
                if alt<d[dst]:
                    d[dst]=alt
                    prev[dst]=cur
                    heappush(q,(alt,dst))
        return d,prev
    
    def __str__(self):
        if self.IsGrid:
            for i in range(self.grid_h):
                print(*self.mp[i*self.grid_w:-~i*self.grid_w])
            return str(str(self.show()))
        else:
            return  str(str(self.show()))

    def show(self):  # hide distance when all distance == 1
        if self.IsGrid:
            rt=[[nd for nd,d in e] for e in self.edges]
            return 'Grid',rt
        else:
            if all([all([d==1 for nd,d in e]) for e in self.edges]):
                rt=[[nd for nd,d in e] for e in self.edges]
                return 'Simplified',rt
            else:
                return self

gr=Graph(init=False)
h,w=LI()

mp,f=gr.gridin(h,w)
print(0/0)
v=gr.bfs(0)

print(max(v))

Submission status: Runtime Error

Solution code:
from collections import deque
H, W = map(int, input().split())

area = [input() for _ in range(H)]

distance = [ [float('inf') for _ in range(W)] for _ in range(H)]
to_search = deque()

for i in range(H):
    for j in range(W):
        if area[i][j] == "#":
            to_search.appendleft((i, j, 0))
            distance[i][j] = 0

didj = [[1, 0], [0. 1], [-1, 0], [0, -1]]
ans = 0

while len(to_search) > 0:
    nowi, nowj, nowd = to_search.pop()
    for di, dj in didj:
        nexti = nowi + di
        nextj = nowj + dj
        if 0 <= nexti <= H and 0 <= nextj <= W:
            if distance[nexti][nextj] > nowd + 1:
                to_search.appendleft((nexti, nextj, nowd + 1))
                distance[nexti][nextj] = nowd + 1
                ans = max(ans, nowd + 1)

print(ans)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline    ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')
# from math import ceil, floor, log2
from collections import deque
# from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations
# from heapq import heapify, heappop, heappush
# import numpy as np
# from numpy import cumsum  # accumulate
import copy

def grid_wall(grid, h, w, wall='#'):
    G = [[wall]*(w+2) for _ in range(h+2)]
    for hi in range(h):
        G[hi+1][1:w+1] = grid[hi]
    return G

def solve():
    H, W = MI()
    g = [[] for _ in range(H)]
    start = []
    white_cnt = 0
    for i in range(H):
        line = LS()
        for j, l in enumerate(line):
            if l == '.': white_cnt = white_cnt + 1
            else: start.append((i+1, j+1))
        g[i] = line

    if white_cnt == 0:
        print(0)

    G = grid_wall(g, H, W, 'x')
    move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
    ans = 0
    while 1:
        next = []
        for x, y in start:

            for dx, dy in move:
                nx, ny = x+dx, y+dy
                if G[nx][ny] == 'x': continue
                elif G[nx][ny] == '#': continue
                else:
                    white_cnt -= 1
                    G[nx][ny] = '#'
                    next.append((nx, ny))
        ans += 1
        # print(G)
        if white_cnt <= 0:
            print(ans)
            return
        start = next.copy()



if __name__ == '__main__':
    solve()

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline    ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')
# from math import ceil, floor, log2
from collections import deque
# from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations
# from heapq import heapify, heappop, heappush
# import numpy as np
# from numpy import cumsum  # accumulate
import copy

def grid_wall(grid, h, w, wall='#'):
    G = [[wall]*(w+2) for _ in range(h+2)]
    for hi in range(h):
        G[hi+1][1:w+1] = grid[hi]
    return G

def solve():
    H, W = MI()
    g = [[] for _ in range(H)]
    start = []
    white_cnt = 0
    for i in range(H):
        line = LS()
        for j, l in enumerate(line):
            if l == '.': white_cnt = white_cnt + 1
            else: start.append((i+1, j+1))
        g[i] = line

    G = grid_wall(g, H, W, 'x')

    move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
    ans = 0
    while 1:
        next = []
        for x, y in start:

            for dx, dy in move:
                nx, ny = x+dx, y+dy
                if G[nx][ny] == 'x': continue
                elif G[nx][ny] == '#': continue
                else:
                    white_cnt -= 1
                    G[nx][ny] = '#'
                    next.append((nx, ny))
        ans += 1
        # print(G)
        if white_cnt == 0:
            print(ans)
            return
        start = next.copy()




if __name__ == '__main__':
    solve()

Submission status: Runtime Error

Solution code:
from collections import deque

INF = float('inf')

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

# 初期の黒('#')の位置からの距離
dist = [[-1]*W for _ in range(H)]

## '#'の位置をキューに追加（＝今回はこれが複数あるので、複数スタートとなる）
black_cells = deque()
for i in range(H):
    for j in range(W):
        if grid[i][j]=="#":
            dist[i][j]=0
            black_cells.append((i,j))

while black_cells:
    x,y=black_cells.popleft()#黒マスのスタート地点
    d=dist[x][y]#スタート地点からの距離
    for dy, dx in ((1, 0), (0, 1), (-1, 0), (0, -1)):
        new_x=x+dx
        new_y=y+dy
        if new_y < 0 or H <= new_y or new_x < 0 or W <= new_x:#範囲からはみ出すとき
            continue
        if dist[new_x][new_y]==-1:
            dist[new_x][new_y]=d+1
            black_cells.append((new_x,new_y))
print(d)

Submission status: Runtime Error

Solution code:
from collections import deque

INF = float('inf')

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

# 初期の黒('#')の位置からの距離
dist = [[-1]*W for _ in range(H)]

## '#'の位置をキューに追加（＝今回はこれが複数あるので、複数スタートとなる）
black_cells = deque()
for i in range(H):
    for j in range(W):
        if grid[i][j]=="#":
            dist[i][j]=0
            black_cells.append((i,j))

whileblack_cells:
    x,y=black_cells.popleft()#黒マスのスタート地点
    d=dist[x][y]#スタート地点からの距離
    for dy, dx in ((1, 0), (0, 1), (-1, 0), (0, -1)):
        new_x=x+dx
        new_y=y+dy
        if new_y < 0 or H <= new_y or new_x < 0 or W <= new_x:#範囲からはみ出すとき
            continue
        if dist[new_x][new_y]==-1:
            dist[new_x][new_y]=d+1
            black_cells.append((new_x,new_y))
print(d)

Submission status: Runtime Error

Solution code:
from collections import deque

INF = float('inf')

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

# 初期の黒('#')の位置からの距離
dist = [[-1]*W for _ in range(H)]

## '#'の位置をキューに追加（＝今回はこれが複数あるので、複数スタートとなる）
black_cells = deque()
for i in range(H):
    for j in range(W):
        if grid[i][j]=="#":
            dist[i][j]=0
            black_cells.append((i,j))

whileblack_cells:
    x,y=black_cells.popleft()#黒マスのスタート地点
    d=dist[x][y]#スタート地点からの距離
    for dy, dx in ((1, 0), (0, 1), (-1, 0), (0, -1)):
        new_x=x+dx
        new_y=y+dy
        if new_y < 0 or H <= new_y or new_x < 0 or W <= new_x:#範囲からはみ出すとき
            continue
        elif dist[new_x][new_y]==-1:
            dist[new_x][new_y]=d+1
            black_cells.append((new_x,new_y))
print(d)

Submission status: Runtime Error

Solution code:
from collections import deque

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

# 初期の黒('#')の位置からの距離
dist = [[-1]*W for _ in range(H)]

## '#'の位置をキューに追加（＝今回はこれが複数あるので、複数スタートとなる）
black_cells = deque()
for i in range(H):
    for j in range(W):
        if grid[i][j]=="#":
            dist[i][j]=0
            black_cells.append((i,j))

while(black_cells):
    x,y=black_cells.popleft()#黒マスのスタート地点
    d=dist[x][y]#スタート地点からの距離
    for dx,dy in ((0,1),(1,0),(-1,0),(0,-1)):#上下左右の色を塗る
        new_x=x+dx
        new_y=y+dy
        if new_y < 0 or H <= new_y or new_x < 0 or W <= new_x:#範囲からはみ出すとき
            continue
        elif dist[new_x][new_y]==-1:
            dist[new_x][new_y]=d+1
            black_cells.append((new_x,new_y))
print(d)

Submission status: Runtime Error

Solution code:
from collections import deque

INF = float('inf')

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

# 初期の黒('#')の位置からの距離
dist = [[-1]*W for _ in range(H)]

## '#'の位置をキューに追加（＝今回はこれが複数あるので、複数スタートとなる）
black_cells = deque()
for i in range(H):
    for j in range(W):
        if grid[i][j]=="#":
            dist[i][j]=0
            black_cells.append((i,j))

while(black_cells):
    x,y=black_cells.popleft()#黒マスのスタート地点
    d=dist[x][y]#スタート地点からの距離
    for dx,dy in ((0,1),(1,0),(-1,0),(0,-1)):#上下左右の色を塗る
        new_x=x+dx
        new_y=y+dy
        if new_y < 0 or H <= new_y or new_x < 0 or W <= new_x:#範囲からはみ出すとき
            continue
        elif dist[new_x][new_y]==-1:
            dist[new_x][new_y]=d+1
            black_cells.append((new_x,new_y))
print(d)

Submission status: Runtime Error

Solution code:
from collections import deque

h, w = map(int, input().split())
a = [list(input()) for _ in range(h)]

d = [[-1] * w for _ in range(h)]
que = deque()
for i in range(h):
    for j in range(w):
        if a[i][j] == '#':
            que.append((j, i))
            d[i][j] = 0

dxdy = [(1, 0), (-1, 0), (0, 1), (0, -1)]

ans = 0
while que:
    x, y = que.popleft()
    for dx, dy in dxdy:
        nx = x + dx
        ny = y + dy
        if 0 <= nx < w and 0 <= ny < h and s[ny][nx] == -1:
            que.append((nx, ny))
            s[ny][nx] = s[y][x] + 1
            ans = max(ans, s[ny][nx])

print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque
H, W = map(int, input().split())
a_list = []
dark = deque()
for h in range(H):
    a = input()
    a_list.append(a)
    for w in range(W):
        if a[w] == '#':
            dark.append([h, w])
ans = 0
distance = [[-1] * W for _ in range(H)]
while dark:
    h, w = dark.popleft()
    for x, y in [[1, 0], [-1, 0], [0, 1], [0, -1]]:
        hx, wy = h + x, w + y
        if (0 <= hx < H) & (0 <= wy < W):
            if distance[hx][wy] == -1:
                distance[hx][wy] = distance[h][w] + 1
                ans = max(ans, distance[hx][wy])
                tmp.append([hx, wy])
    dark = tmp
print(ans + 1)

Submission status: Runtime Error

Solution code:
H, W = map(int, input().rstrip().split())
checked = [[-1]*W for i in range(H)]
black_list = []
# 初期化
# 0 => 黒、 -1 => 白
for i in range(H):
    row = input().rstrip()
    for j in range(W):
        if row[j] == "#":
            checked[i][j] = 0
            black_list.append((i, j))


queue = deque([])
# 黒の周辺4方向のうち、白だったら黒にする
while black_list:
    tmp = []
    for x, y in black_list:
        # 上
        if x-1 > -1 and checked[x-1][y] == -1:
            checked[x-1][y] = checked[x][y] + 1
            tmp.append((x-1, y))
        # 下
        if x+1 < H and checked[x+1][y] == -1:
            checked[x+1][y] = checked[x][y] + 1
            tmp.append((x+1, y))
        # 左
        if y-1 > -1 and checked[x][y-1] == -1:
            checked[x][y-1] = checked[x][y-1] + 1
            tmp.append((x, y-1))

        # 右
        if y+1 < W and checked[x][y+1] == -1:
            checked[x][y+1] = checked[x][y+1] + 1
            tmp.append((x, y+1))

    black_list = tmp


ans = 0
for i in range(H):
    for j in range(W):
        if ans < checked[i][j]:
            ans = checked[i][j]
print(ans)

Submission status: Runtime Error

Solution code:

from collections import deque

# class Point():
#   def __init__(self, x, y):
#     self.x = x
#     self.y = y
  
#   def __str__(self):
#     # return f"Point(x={self.x}, y={self.y})"
#     return "Point(x=" + str(self.x) + ", y=" + str(self.y) + ")"

#   def __repr__(self):
#     return self.__str__()

def parse():
  H, W = map(int, input().split(" "))
  grid = []
  black_points = set()
  for y in range(H):
    line = input()
    grid.append(list(line))
    for x, c in enumerate(line):
      if c == "#":
        black_points.add((x, y))
  return H, W, grid, black_points

def print_grid(grid):
  H = len(grid)
  print("grid:")
  for y in range(H):
    print(grid[y])

def is_all_black(grid):
  H = len(grid)
  W = len(grid[0])
  for y in range(H):
    for x in range(W):
      if grid[y][x] == ".": return False
  return True

def main():
  H, W, grid, black_points = parse()
  # print(H, W, grid)

  # vecs = [Point(0, -1), Point(0, 1), Point(-1, 0), Point(1, 0)]
  visited = [[H * W for y in range(H)] for x in range(W)]
  for black_point in black_points:
    visited[black_point[1]][black_point[0]] = 0
  q = deque(black_points)
  vecs = [(0, -1), (0, 1), (-1, 0), (1, 0)]
  
  # 初期の黒色の場所を追加
  # black_points = set()
  # for y in range(H):
  #   for x in range(W):
  #     if grid[y][x] == "#":
  #       black_points.add((x, y))
  #       # black_points.append(Point(x, y))
  # print(black_points)
  # exit(0)

  # 最大長で決定する
  # ans = 0
  # for black_point in black_points:
  #   x_right_len = 0
  #   x_left_len = 0
  #   for x in range(black_point[0] + 1, W, 1):
  #     if grid[black_point[1]][x] == "#": break
  #     x_right_len += 1
  #   for x in range(black_point[0] - 1, -1, -1):
  #     if grid[black_point[1]][x] == "#": break
  #     x_left_len += 1

  #   y_up_len = 0
  #   y_down_len = 0
  #   for y in range(black_point[1] + 1, H, 1):
  #     if grid[y][black_point[0]] == "#": break
  #     y_up_len += 1
  #   for y in range(black_point[0] - 1, -1, -1):
  #     if grid[y][black_point[0]] == "#": break
  #     y_down_len += 1

  #   ans = max(ans, x_right_len, x_left_len, y_up_len, y_down_len)
  # print(ans)
  # exit(0)

  ans = 0
  while len(q) > 0:
    black_point = q.popleft()

    # for black_point in black_points:
    # print("black_point:", black_point)
    for vec in vecs:
      x = black_point[0] + vec[0]
      if x < 0 or x >= W: continue

      y = black_point[1] + vec[1]
      if y < 0 or y >= H: continue
      
      if visited[y][x] > 0: continue
      
      # grid[y][x] = "#"
      visited[y][x] = visited[black_point[1]][black_point[0]] + 1
      # next_black_points.add((x, y))
      q.append((x, y))
    
    # black_points = next_black_points
    # ans += 1

    # print("next_black_points:", next_black_points)
    # print_grid(grid)
    # input()
  
  ans = 0
  for y in range(H):
    max_val = max(visited[y][:])
    ans = ans if ans > max_val else max_val
  print(ans)

if __name__ == "__main__":
  main()