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: Accepted

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,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]
            for j in s:
                self.mp.append(mp_def[j])
        for dd in [1,w]:
            r_end=0
            for node in range(self.node_size):
                r_end+=1
                if r_end==w:
                    r_end=0
                nx=node+dd
                if nx<0 or self.node_size<=nx or (dd==1 and r_end==0):
                    continue
                if self.mp[nx]==0:
                    self.edges[node].append(nx)
                if self.mp[node]==0:
                    self.edges[nx].append(node)
        return 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([x])
        q=deque([i for i,j in enumerate(self.mp) if j==1])
        v=[None]*self.node_size
        #v[x]=root_v
        for y in q:v[y]=root_v
        while q:
            c=q.popleft()
            for nb 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()

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

print(max(v))

Submission status: Accepted

Solution code:
import sys
from collections import deque
sys.setrecursionlimit(10 ** 7)

def solve():
    H, W = map(int, input().split())
    M = [[] for _ in range(H)]
    queue = deque()
    for i in range(H):
        M[i] = list(input())
        for j in range(W):
            if M[i][j] == '#':
                queue.append((i, j))
    ans = 0
    while queue:
        # 今の地点から1ステップ変化
        n = len(queue)
        flag = False
        for _ in range(n):
            cy, cx = queue.popleft()
            for dy, dx in ((-1, 0), (0, 1), (1, 0), (0, -1)):
                ny, nx = cy + dy, cx + dx
                if 0 <= nx < W and 0 <= ny < H and M[ny][nx] == '.':
                    M[ny][nx] = '#'
                    flag = True
                    queue.append((ny, nx))
        if flag:
            ans += 1
    print(ans)


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
from collections import deque
h, w = map(int, input().split())
n = h*w


def to_v(i, j):
    return i*w+j


init_vs = []
for i in range(h):
    for j, x in enumerate(input()):
        if x == '#':
            init_vs.append(to_v(i, j))


INF = 10**18
dist = [INF]*n
for v in init_vs:
    dist[v] = 0


def generate_v2(v):
    i, j = divmod(v, w)
    if 0 < i:
        yield v-w
    if i < h-1:
        yield v+w
    if 0 < j:
        yield v-1
    if j < w-1:
        yield v+1


def bfs(init_vs):
    next_v = deque([*init_vs])
    while next_v:
        v = next_v.popleft()
        for v2 in generate_v2(v):
            if dist[v2] <= dist[v]+1:
                continue
            dist[v2] = dist[v]+1
            next_v.append(v2)


bfs(init_vs)
print(max(dist))

Submission status: Accepted

Solution code:
from collections import deque
import sys
input = sys.stdin.readline

def bfs():
    H, W = map(int, input().split())
    ls = deque([])
    D = [[True] * (W+2)]
    D += ([[True] + [False]*W + [True] for i in range(H)])
    D.append([True]*(W+2))
    for i in range(H):
        line = input()
        for j in range(W):
            if line[j] == "#":
                ls.append([i+1, j+1, 0])
                D[i+1][j+1] = True

    while len(ls) > 0:
        h, w, depth = ls.popleft()
        if not D[h+1][w]:
            ls.append([h+1, w, depth+1])
            D[h+1][w] = True
        if not D[h-1][w]:
            ls.append([h-1, w, depth+1])
            D[h-1][w] = True
        if not D[h][w+1]:
            ls.append([h, w+1, depth+1])
            D[h][w+1] = True
        if not D[h][w-1]:
            ls.append([h, w-1, depth+1])
            D[h][w-1] = True

    return depth
    
print(bfs())

Submission status: Accepted

Solution code:
from sys import stdin
import numpy as np
from numba import njit

@njit("i8(i8[:,:],i8,i8)",cache=True)
def search(grid,h,w):
    q=np.zeros(2*10**6+4,dtype=np.int64)
    now=0
    for i in range(h):
        for j in range(w):
            if grid[i][j]==1:
                q[now]=i
                q[now+1]=j
                now+=2

    now,nex=0,now
    cnt=0
    while now!=nex:
        tmp=nex
        for i in range(now,nex,2):
            y=q[i]
            x=q[i+1]
            for dy,dx in (-1,0),(1,0),(0,-1),(0,1):
                ny=y+dy
                nx=x+dx
                if 0<=ny<h and 0<=nx<w:
                    if grid[ny][nx]==0:
                        grid[ny][nx]=1
                        q[tmp]=ny
                        q[tmp+1]=nx
                        tmp+=2

        now,nex=nex,tmp
        cnt+=1

    return cnt-1

def main():
    #入力
    readline=stdin.readline
    h,w=map(int,readline().split())
    grid=[readline().strip() for _ in range(h)]
    grid=np.array([[1 if grid[i][j]=="#" else 0 for j in range(w)] for i in range(h)],dtype=np.int64)
    print(search(grid,h,w))

if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
from sys import stdin
import numpy as np
from numba import njit

@njit("i8(i8[:,:],i8,i8)")
def search(grid,h,w):
    q=np.zeros(2*10**6+4,dtype=np.int64)
    now=0
    for i in range(h):
        for j in range(w):
            if grid[i][j]==1:
                q[now]=i
                q[now+1]=j
                now+=2

    now,nex=0,now
    cnt=0
    while now!=nex:
        tmp=nex
        for i in range(now,nex,2):
            y=q[i]
            x=q[i+1]
            for dy,dx in (-1,0),(1,0),(0,-1),(0,1):
                ny=y+dy
                nx=x+dx
                if 0<=ny<h and 0<=nx<w:
                    if grid[ny][nx]==0:
                        grid[ny][nx]=1
                        q[tmp]=ny
                        q[tmp+1]=nx
                        tmp+=2

        now,nex=nex,tmp
        cnt+=1

    return cnt-1

def main():
    #入力
    readline=stdin.readline
    h,w=map(int,readline().split())
    grid=[readline().strip() for _ in range(h)]
    grid=np.array([[1 if grid[i][j]=="#" else 0 for j in range(w)] for i in range(h)],dtype=np.int64)
    print(search(grid,h,w))

if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque


def BFS():
    point=0
    color=[["white" for _ in range(w)] for _ in range(h)]
    D=[[0 for _ in range(w)] for _ in range(h)]

    queue=deque([])
    for i in range(h):
        for j in range(w):
            if A[i][j]=="#":
                color[i][j]="gray"
                queue.append([i,j])
                D[i][j]=0

    while len(queue)>0:
        x,y=queue.popleft()
        for a,b in [[1,0],[-1,0],[0,1],[0,-1]]:
            X,Y=x+a,y+b
            if 0<=X<h and 0<=Y<w:
                if color[X][Y]=="white":
                    color[X][Y]="gray"
                    D[X][Y]=D[x][y]+1
                    point=max(point,D[X][Y])
                    queue.append([X,Y])
        color[x][y]="black"

    return point


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

Submission status: Accepted

Solution code:
from collections import deque
import sys
input = sys.stdin.readline

H ,W = map(int, input().split())#↓H行数 →W列数
List = [list(str(input())) for i in range(H)]
#H=3
#W=3
#List=[['.', '.', '.'], ['.', '#', '.'], ['.', '.', '.']]
cheak=[['0' for i in range(W)] for j in range(H)]

q = deque([])

for h in range(H):
    for w in range(W):
        if List[h][w]=='#':
            cheak[h][w]='1'
            q.append([h,w])
#print(List)
#print(cheak)
move=[[1,0],[-1,0],[0,1],[0,-1]]
num=-1
#print(q)
while q:
    for rt in range(len(q)):
        i=q.popleft()
        for u in move:
            if 0<=i[0]+u[0]<=H-1 and 0<=i[1]+u[1]<=W-1 and cheak[i[0]+u[0]][i[1]+u[1]]=='0':
                q.append([i[0]+u[0],i[1]+u[1]])
                cheak[i[0]+u[0]][i[1]+u[1]]='1'
    #print(cheak)
    num+=1
print(num)

Submission status: Accepted

Solution code:
from collections import deque
def solve():
    max_cost = 0
    stack = deque()
    used = [[False for _ in range(W)] for _ in range(H)]
    for i in range(H):
        for j in range(W):
            if A[i][j] == '.':
                continue
            stack.append([(i, j), 0])
            used[i][j] = True
    while stack:
        (i, j), cost = stack.popleft()
        max_cost = max(max_cost, cost)
        for x, y in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
            if not 0 <= x < H or not 0 <= y < W or used[x][y]:
                continue
            stack.append([(x, y), cost + 1])
            used[x][y] = True
    print(max_cost)

if __name__ == "__main__":
    H, W = map(int, input().split())
    A = []
    for _ in range(H):
        A.append(list(input()))
    solve()

Submission status: Accepted

Solution code:
from collections import deque

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

b = [[-1 for _ in range(w)] for _ in range(h)]

q = deque()

for i in range(h):
    for j in range(w):
        if(a[i][j] == "#"):
            b[i][j] = 0
            q.append(i)
            q.append(j)
kotae = 0
while(len(q)):
    x = int(q.popleft())
    y = int(q.popleft())
    dx = [0, 0, -1, 1]
    dy = [-1, 1, 0, 0]

    for i in range(4):
        if(0 <= x + dx[i] and x + dx[i] < h and 0 <= y + dy[i] and y + dy[i] < w):
            if(b[x+dx[i]][y+dy[i]] == -1):
                q.append(x + dx[i])
                q.append(y + dy[i])
                b[x+dx[i]][y+dy[i]] = b[x][y] + 1
                kotae = max(kotae, b[x+dx[i]][y+dy[i]])
print(kotae)

Submission status: Accepted

Solution code:
from collections import deque
import sys


H, W = [int(_) for _ in input().split()]

M = []
q = deque([])
for i in range(H):
    A = input()
    M.append(list(A))
    for j in range(W):
        if A[j] == '#':
            q.append([j, i, 0])

depth_now = 0
depth = 0
count = 0
while len(q) > 0:
    p = q.popleft()
    x = p[0]
    y = p[1]
    depth = p[2]
    if x - 1 >= 0 and M[y][x-1] == '.':
        q.append([x-1, y, depth+1])
        M[y][x-1] = '#'
    if x + 1 < W and M[y][x+1] == '.':
        q.append([x+1, y, depth+1])
        M[y][x+1] = '#'
    if y - 1 >= 0 and M[y-1][x] == '.':
        q.append([x, y-1, depth+1])
        M[y-1][x] = '#'
    if y + 1 < H and M[y+1][x] == '.':
        q.append([x, y+1, depth+1])
        M[y+1][x] = '#'
print(depth)

Submission status: Accepted

Solution code:
def main():
    H, W = map(int, input().split())
    g = []
    q = []
    cnt = 0
    for h in range(H):
        A = str(input())
        row = []
        for w in range(W):
            row.append(A[w])
            if A[w] == '#':
                cnt += 1
                q.append([h, w])
        g.append(row)
    ans = 0
    dh = [1, 0, 0, -1]
    dw = [0, -1, 1, 0]
    while cnt < H * W:
        ans += 1
        nextq = []
        while q:
            h, w = q.pop()
            for i in range(4):
                nh = h + dh[i]
                nw = w + dw[i]
                if 0 <= nh < H and 0 <= nw < W and g[nh][nw] == '.':
                    g[nh][nw] = '#'
                    nextq.append([nh, nw])
                    cnt += 1
        q = nextq
    print(ans)
main()

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
grid=[[-1]*w for _ in range(h)]
from collections import deque
que=deque()
for i in range(h):
    s=list(input())
    for j in range(w):
        if s[j]=='#':
            grid[i][j]=0
            que.append((i,j))
dirc=[(1,0),(-1,0),(0,1),(0,-1)]

while que:
    kuro=que.popleft()
    n=grid[kuro[0]][kuro[1]]
    for dx,dy in dirc:
        x=kuro[0]+dx
        y=kuro[1]+dy
        if 0<=x<h and 0<=y<w and grid[x][y]==-1:
            grid[x][y]=n+1
            que.append((x,y))

ans=0
for i in range(h):
    ans=max(ans,max(grid[i]))
print(ans)

Submission status: Accepted

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:
    y,x=black_cells.popleft()#黒マスのスタート地点
    d=dist[y][x]#スタート地点からの距離
    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_y][new_x]==-1:
            dist[new_y][new_x]=d+1
            black_cells.append((new_y,new_x))
print(d)

Submission status: Accepted

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))

d = 0
while black_cells:
    # キューとして使うのでpop()ではなくpopleft()
    h, w = black_cells.popleft()
    d = dist[h][w]
    for dy, dx in ((1, 0), (0, 1), (-1, 0), (0, -1)):
        new_h = h + dy
        new_w = w + dx
        if new_h < 0 or H <= new_h or new_w < 0 or W <= new_w:
            continue
        if dist[new_h][new_w] == -1:  # セルが白('.')であるのと同義
            dist[new_h][new_w] = d+1
            black_cells.append((new_h, new_w))
print(d)

Submission status: Accepted

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))

d = 0
while black_cells:
    # キューとして使うのでpop()ではなくpopleft()
    h, w = black_cells.popleft()
    d = dist[h][w]
    for dy, dx in ((1, 0), (0, 1), (-1, 0), (0, -1)):
        new_h = h + dy
        new_w = w + dx
        if new_h < 0 or H <= new_h or new_w < 0 or W <= new_w:
            continue
        if dist[new_h][new_w] == -1:  # セルが白('.')であるのと同義
            dist[new_h][new_w] = d+1
            black_cells.append((new_h, new_w))
print(d)

Submission status: Accepted

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 h in range(H):
    for w in range(W):
        if grid[h][w] == '#':
            black_cells.append((h, w))
            dist[h][w] = 0

d = 0
while black_cells:
    # キューとして使うのでpop()ではなくpopleft()
    h, w = black_cells.popleft()
    d = dist[h][w]
    for dy, dx in ((1, 0), (0, 1), (-1, 0), (0, -1)):
        new_h = h + dy
        new_w = w + dx
        if new_h < 0 or H <= new_h or new_w < 0 or W <= new_w:
            continue
        if dist[new_h][new_w] == -1:  # セルが白('.')であるのと同義
            dist[new_h][new_w] = d+1
            black_cells.append((new_h, new_w))
print(d)

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
from collections import deque
directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]

def main():
    H, W = map(int, readline().rstrip().split())
    mat = [list(readline().rstrip()) for _ in range(H)]

    start = []
    for h in range(H):
        for w in range(W):
            if mat[h][w] == '#':
                start.append((h, w))
    
    res = 0
    que = deque(start)
    while que:
        next_que = deque()
        for h, w in que:
            for dh, dw in directions:
                if not (0 <= h+dh < H and 0 <= w+dw < W):
                    continue
                if mat[h+dh][w+dw] == '#':
                    continue
                mat[h+dh][w+dw] = '#'
                next_que.append((h+dh, w+dw))

        res += 1
        que = next_que

    print(res - 1)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
from collections import deque
directions = ((-1, 0), (1, 0), (0, -1), (0, 1))

def main():
    H, W = map(int, readline().rstrip().split())
    mat = [list(readline().rstrip()) for _ in range(H)]

    start = []
    for h in range(H):
        for w in range(W):
            if mat[h][w] == '#':
                start.append((h, w))
    
    res = 0
    que = deque(start)
    while que:
        next_que = deque()
        for h, w in que:
            for dh, dw in directions:
                if not (0 <= h+dh < H and 0 <= w+dw < W):
                    continue
                if mat[h+dh][w+dw] == '#':
                    continue
                mat[h+dh][w+dw] = '#'
                next_que.append((h+dh, w+dw))

        res += 1
        que = next_que

    print(res - 1)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
from collections import deque
directions = ((-1, 0), (1, 0), (0, -1), (0, 1))

def main():
    H, W = map(int, readline().rstrip().split())
    mat = [list(readline().rstrip()) for _ in range(H)]

    start = []
    for h in range(H):
        for w in range(W):
            if mat[h][w] == '#':
                start.append((h, w))
    
    res = 0
    que = deque(start)
    while que:
        next_que = []
        while que:
            h, w = que.popleft()
            for dh, dw in directions:
                if not (0 <= h+dh < H and 0 <= w+dw < W):
                    continue
                if mat[h+dh][w+dw] == '#':
                    continue
                mat[h+dh][w+dw] = '#'
                next_que.append((h+dh, w+dw))

        res += 1
        que = deque(next_que)

    print(res - 1)


if __name__ == '__main__':
    main()