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:
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque, OrderedDict
from copy import deepcopy
from fractions import gcd
from functools import lru_cache, reduce
from math import ceil, floor
from sys import setrecursionlimit

import heapq as hq
import itertools as its
import operator as op


# globals
inf = float('inf')
H, W = 0, 0
A = []


def set_inputs():
    global H, W, A
    H, W = get_li()
    A = [get_str() for _ in range(H)]
    return


def main():
    set_inputs()
    # ----------MAIN----------
    stage = [[0 for _ in range(W)] for _ in range(H)]
    remaining = deque()
    for i, ai_ in enumerate(A):
        for j, a in enumerate(ai_):
            if a == ".":
                continue
            stage[i][j] = 1
            remaining.append((i, j))
    ans = 0
    while remaining:
        _next = deque()
        for (i, j) in remaining:
            stage[i][j] = 2
            if i > 0 and stage[i-1][j] == 0:
                stage[i-1][j] = 1
                _next.append((i-1, j))
            if i < H - 1 and stage[i+1][j] == 0:
                stage[i+1][j] = 1
                _next.append((i+1, j))
            if j > 0 and stage[i][j-1] == 0:
                stage[i][j-1] = 1
                _next.append((i, j-1))
            if j < W - 1 and stage[i][j+1] == 0:
                stage[i][j+1] = 1
                _next.append((i, j+1))
        remaining = _next
        ans += 1
    if ans == 0:
        print(0)
    else:
        print(ans - 1)
    return


def get_int():
    return int(input())


def get_float():
    return float(input())


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


def get_li():
    return [int(i) for i in input().split()]


def get_lf():
    return [float(f) for f in input().split()]


def get_lc():
    return list(input().strip())


def get_data(n, types, sep=None):
    if len(types) == 1:
        return [types[0](input().strip()) for _ in range(n)]
    return list(zip(*(
        [t(x) for t, x in zip(types, input().strip().split(sep=sep))]
        for _ in range(n)
    )))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque
H, W = map(int, input().split())
hw = [list(input().strip()) for _ in range(H)]
b = deque()
for h in range(H):
    for w in range(W):
        if hw[h][w] == '#':
            b.append([h, w, 0])

ans = 0
while len(b) > 0:
    h, w, d = b.popleft()
    d += 1
    for y, x in [[1, 0], [-1, 0], [0, 1], [0, -1]]:
        nh, nw = h + y, w + x
        if nh >= 0 and nh < H and nw >= 0 and nw < W and hw[nh][nw] == '.':
            b.append([nh, nw, d])
            if ans < d:
                ans = d
            hw[nh][nw] = "#"
print(ans)

Submission status: Accepted

Solution code:
from collections import deque

H,W = map(int,input().split()) 
A = [[0]*W for _ in range(H)]
M = 0
queue = deque()
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.popleft()
  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: Accepted

Solution code:
from collections import deque
from itertools import chain
H, W = map(int, input().split())
G = chain.from_iterable([[s == '#' for s in input()] for _ in range(H)])
dist = [0]*(H*W)
B = deque([i for i, g in enumerate(G) if g])
visited = set(B)
while B:
    vij = B.pop()
    for dij in (W, -W, 1, -1):
        nij = vij + dij
        if (dij == 1 and not nij % W) or (dij == -1 and not (nij+1) % W) or not (0 <= nij < H*W) or nij in visited:
            continue
        visited.add(nij)
        dist[nij] = 1 + dist[vij]
        B.appendleft(nij)
print(max(dist))

Submission status: Accepted

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

inf = float('inf')

def solve(H: int, W: int, A: "List[str]"):
    dist = [[inf] * W for h in range(H)]
    for h in range(1, H):
        for w in range(1, W):
            if A[h][w] == '#':
                dist[h][w] = 0
            else:
                dist[h][w] = min(dist[h-1][w], dist[h][w-1]) + 1
    
    dmax = 0
    for h in range(H-1, -1, -1):
        for w in range(W-1, -1, -1):
            if A[h][w] == '#':
                dist[h][w] = 0
            elif h+1 <= H-1 and w+1 <= W-1:
                dist[h][w] = min(dist[h][w], min(dist[h+1][w], dist[h][w+1]) + 1)
            elif w+1 == W and h+1 <= H-1:
                dist[h][w] = min(dist[h][w], dist[h+1][w] + 1)
            elif h+1 == H and w+1 <= W-1:
                dist[h][w] = min(dist[h][w], dist[h][w+1] + 1)
            dmax = max(dist[h][w], dmax)
    print(dmax) 
    return


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

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque

H, W = map(int, input().split())
A = [list(input()) for _ in range(H)]
blacks = deque([])
for h in range(H):
  for w in range(W):
    if A[h][w] == "#":
      blacks.append((h, w))
count = 0
while len(blacks) > 0:
  newblacks = deque([])
  while len(blacks) > 0:
    b = blacks.popleft()
    for y, x in zip((b[0]-1, b[0], b[0], b[0]+1), (b[1], b[1]-1, b[1]+1, b[1])):
      if y < 0 or y >= H or x < 0 or x >= W:
        continue
      if A[y][x] == ".":
        newblacks.append((y, x))
      A[y][x] = "#"
  blacks = newblacks
  count += 1
print(count-1)

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

Q = deque()
for i in range(H):
    for j in range(W):
        if A[i][j] == "#":
            Q.append((i, j, 0))

ma = 0
while Q:
    i, j, dist = Q.popleft()
    ma = max(ma, dist)
    for ni, nj in [(i + 1, j), (i, j + 1), (i - 1, j), (i, j - 1)]:
        if 0 <= ni < H and 0 <= nj < W and A[ni][nj] == ".":
            A[ni][nj] = "#"
            Q.append((ni, nj, dist + 1))

print(ma)

Submission status: Accepted

Solution code:
from collections import deque

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

bl = [[False] * W for _ in range(H)]
dq = deque()

for r in range(H):
    for c in range(W):
        if a[r][c] == '#':
            bl[r][c] = True
            dq.append((r, c, 0))


def in_range(r, c):
    return 0 <= r < H and 0 <= c < W


dr_s = (0, 0, -1, 1)
dc_s = (-1, 1, 0, 0)

while dq:
    r, c, d = dq.popleft()
    for dr, dc in zip(dr_s, dc_s):
        nr = r + dr
        nc = c + dc
        if not in_range(nr, nc): continue
        if bl[nr][nc]: continue
        bl[nr][nc] = True
        dq.append((nr, nc, d + 1))

print(d)

Submission status: Accepted

Solution code:
# AtCoder Grand Contest 033
# https://atcoder.jp/contests/agc033
import sys

s2nn = lambda s: [int(c) for c in s.split(' ')]
ss2nn = lambda ss: [int(s) for s in list(ss)]
ss2nnn = lambda ss: [s2nn(s) for s in list(ss)]
i2s = lambda: sys.stdin.readline().rstrip()
i2n = lambda: int(i2s())
i2nn = lambda: s2nn(i2s())
ii2ss = lambda n: [sys.stdin.readline() for _ in range(n)]
ii2nn = lambda n: ss2nn(ii2ss(n))
ii2nnn = lambda n: ss2nnn(ii2ss(n))

import datetime

def main():
    H, W = i2nn()
    HW = H * W
    A = ii2ss(H)
    A = [[0 if s == '#' else HW for s in line] for line in A]
    for i in range(H):
        for j in range(1, W):
            if A[i][j-1]+1 < A[i][j]:
                A[i][j] = A[i][j-1]+1
        for j in range(W-2, -1, -1):
            if A[i][j+1]+1 < A[i][j]:
                A[i][j] = A[i][j+1]+1
    for j in range(W):
        for i in range(1, H):
            if A[i-1][j]+1 < A[i][j]:
                A[i][j] = A[i-1][j]+1
        for i in range(H-2, -1, -1):
            if A[i+1][j]+1 < A[i][j]:
                A[i][j] = A[i+1][j]+1
    ans = 0
    for i in range(H):
        for j in range(W):
            if A[i][j] > ans:
                ans = A[i][j]
    print(ans)

main()

Submission status: Accepted

Solution code:
#ref: https://atcoder.jp/contests/agc033/submissions/5260580

import sys
import numpy as np

def main():
    input = sys.stdin.readline
    H, W = map(int, input().split())
    INF = H * W
    dp = [[INF if c == '.' else 0 for c in input().strip()] for _ in range(H)]
    dp = np.array(dp)

    for i in range(1, H):
        dp[i, :] = np.minimum(dp[i, :], dp[i-1, :] + 1)

    for i in range(H-2, -1, -1):
        dp[i, :] = np.minimum(dp[i, :], dp[i+1, :] + 1)

    for i in range(1, W):
        dp[:, i] = np.minimum(dp[:, i], dp[:, i-1] + 1)

    for i in range(W-2, -1, -1):
        dp[:, i] = np.minimum(dp[:, i], dp[:, i+1] + 1)

    return np.max(dp)

if __name__ == '__main__':
    print(main())

Submission status: Accepted

Solution code:
def main():
    high, width = map(int, input().split())
    data = [list(input()) for i in range(high)]

    now_list = []
    next_list = []

    for i in range(high):
        for j in range(width):
            if data[i][j] == '#':
                now_list.append([i, j])

    count = 0

    while 1:
        for now_data in now_list:
            i, j = now_data

            kari_i1, kari_i2 = i - 1, i + 1
            kari_j1, kari_j2 = j - 1, j + 1

            if kari_i1 >= 0:
                a, b = kari_i1, j
                if data[a][b] == '.':
                    next_list.append([a, b])
                    data[a][b] = '#'

            if kari_i2 <= high - 1:
                a, b = kari_i2, j
                if data[a][b] == '.':
                    next_list.append([a, b])
                    data[a][b] = '#'

            if kari_j1 >= 0:
                a, b = i, kari_j1
                if data[a][b] == '.':
                    next_list.append([a, b])
                    data[a][b] = '#'

            if kari_j2 <= width - 1:
                a, b = i, kari_j2
                if data[a][b] == '.':
                    next_list.append([a, b])
                    data[a][b] = '#'

        now_list = next_list
        next_list = []


        if len(now_list) == 0:
            break
        else:
            count += 1


    print(count)



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
h,w= map(int, input().split())
s_list = []
b_list = []
for i in range(h):
    li = input()
    aa = []
    for j in range(w):
        aa.append(li[j])
        if aa[j] == '#':
            b_list.append((i, j))
    s_list.append(aa)
ans = 0
while True:
    bb_list = []
    for p in b_list:
        pp = [(p[0]-1, p[1]), (p[0]+1, p[1]), (p[0], p[1]-1), (p[0], p[1]+1)]
        for ppp in pp:
            if (0 <= ppp[0] < h) and (0 <= ppp[1] < w):
                if s_list[ppp[0]][ppp[1]] == '.':
                    s_list[ppp[0]][ppp[1]] = '#'
                    bb_list.append((ppp[0], ppp[1]))
    # ここで複数回同じbをやらなくて済むようにしている
    b_list = bb_list
    if len(b_list) == 0:
        break
    ans += 1
    # print(x)
print(ans)

Submission status: Accepted

Solution code:
from collections import deque

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

dist = [[-1] * W for _ in range(H)]
dq = deque()

for r in range(H):
    for c in range(W):
        if a[r][c] == '#':
            dist[r][c] = 0
            dq.append((r, c))


def in_range(r, c):
    return 0 <= r < H and 0 <= c < W


dr_s = (0, 0, -1, 1)
dc_s = (-1, 1, 0, 0)

d = 0
while dq:
    r, c = dq.popleft()
    d = dist[r][c]
    for dr, dc in zip(dr_s, dc_s):
        nr = r + dr
        nc = c + dc
        if not in_range(nr, nc): continue
        if dist[nr][nc] != -1: continue
        dist[nr][nc] = d + 1
        dq.append((nr, nc))

print(d)

Submission status: Accepted

Solution code:
import sys
from collections import deque


fin = sys.stdin.readline
H, W = [int(elem) for elem in fin().split()]
A_list = [fin().rstrip("\n") for _ in range(H)]
assert len(A_list[0]) == W

visited = [[False] * W for _ in range(H)]
que = deque((i, j, 0) for i in range(H) for j in range(W) if A_list[i][j] == "#")
max_dist = 0
while que:
    i, j, dist = que.popleft()
    for next_i, next_j in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
        if not (0 <= next_i < H and 0 <= next_j < W):
            continue
        elif visited[next_i][next_j]:
            continue
        elif A_list[next_i][next_j] == "#":
            continue
        else:
            que.append((next_i, next_j, dist + 1))
            visited[next_i][next_j] = True
            max_dist = max(max_dist, dist + 1)
print(max_dist)

Submission status: Accepted

Solution code:
from collections import deque
H,W=map(int,input().split())
A=[list(input()) for i in range(H)]
q=deque([])
dist=[[-1 for j in range(W)] for i in range(H)]
for i in range(H):
    for j in range(W):
        if A[i][j]=="#":
            q.append((i,j))
            dist[i][j]=0
dx=[-1,1,0,0]
dy=[0,0,1,-1]
while(len(q)>0):
    x,y=q.popleft()
    for k in range(4):
        nx=x+dx[k]
        ny=y+dy[k]
        if not(0<=nx<H and 0<=ny<W):
            continue
        if dist[nx][ny]==-1:
            dist[nx][ny]=dist[x][y]+1
            q.append((nx,ny))
print(max([max(i) for i in dist]))

Submission status: Accepted

Solution code:
from collections import deque

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

# input black cells
black_cells = []

for h in range(H):
    line = list(input())
    for w in range(W):
        if line[w] == "#":
            black_cells.append(h * W + w)


# Graph
def r(p):
    q_list = []
    h = p // W
    w = p % W
    if h != 0:
        q_list.append(p - W)
    if h != H-1:
        q_list.append(p + W)
    if w != 0:
        q_list.append(p - 1)
    if w != W-1:
        q_list.append(p + 1)
    return q_list


queue = deque(black_cells)
d = [10000] * (H * W)
for i in black_cells:
    d[i] = 0

# dijkstra
while len(queue) > 0:
    p = queue.popleft()
    for q in r(p):
        if d[q] > d[p] + 1:
            d[q] = d[p] + 1
            queue.append(q)

print(max(d))

Submission status: Accepted

Solution code:
import numpy as np

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

status = np.full((H, W), H*W, dtype=int)
for i in range(H):
    s = input()
    for j in range(W):
        if s[j] == "#":
            status[i,j] = 0

for h in range(1, H):
    status[h, :] = np.minimum(status[h, :], status[h-1, :] + 1)
for h in range(0, H-1)[::-1]:
    status[h, :] = np.minimum(status[h, :], status[h+1, :] + 1)
for w in range(1, W):
    status[:, w] = np.minimum(status[:, w], status[:, w-1] + 1)
for w in range(0, W-1)[::-1]:
    status[:, w] = np.minimum(status[:, w], status[:, w+1] + 1)

print(np.max(status))

Submission status: Accepted

Solution code:
import collections

H,W = map(int, input().split())
grid = [0]*(H*W)
black = collections.deque()
for i in range(H):
  A_i = input()
  for j in range(W):
    grid[W*i + j] = 0 if A_i[j] == '#' else -1
    if A_i[j] == '#':
      black.append(W*i + j)

ans = 0
while True:
  black_new = collections.deque()
  while len(black) > 0:
    i = black.pop()
    if i - W >= 0:
      if grid[i - W] == -1:
        grid[i - W] = ans + 1
        black_new.append(i-W)
    if i - 1 >= 0 and i%W != 0:
      if grid[i - 1] == -1:
        grid[i - 1] = ans + 1
        black_new.append(i-1)
    if i + 1 <= H*W-1 and i%W != W-1:
      if grid[i + 1] == -1:
        grid[i + 1] = ans + 1
        black_new.append(i+1)
    if i + W <= H*W-1:
      if grid[i + W] == -1:
        grid[i + W] = ans + 1
        black_new.append(i+W)
  black = black_new
  if len(black) == 0:
    print(ans)
    break
  ans += 1

Submission status: Accepted

Solution code:
from collections import deque

H, W = map(int, input().split())
A_array = [input() for i in range(H)]
adjusted_array = ((0, 1), (-1, 0), (0, -1), (1, 0))

distance = [[-1] * W for i in range(H)]

que = deque()

for i in range(H):
    for j in range(W):
        if A_array[i][j] == "#":
            distance[i][j] = 0
            que.append((i, j))
# print(que)

while (que):
    i, j = que.popleft()
    for adjusted in adjusted_array:
        x = j + adjusted[1]
        y = i + adjusted[0]
        if x >= W or x < 0 or y >= H or y < 0 or distance[y][x] != -1:
            continue
        distance[y][x] = distance[i][j] + 1
        que.append((y, x))

print(max([max(distance[i]) for i in range(H)]))

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

Q = deque((i, j, 0) for i in range(H) for j in range(W) if A[i][j] == "#")

ans = 0
while Q:
    i, j, dist = Q.popleft()
    ans = max(ans, dist)
    for di, dj in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
        ni, nj = i + di, j + dj
        if 0 <= ni < H and 0 <= nj < W and A[ni][nj] == ".":
            A[ni][nj] = "#"
            Q.append((ni, nj, dist + 1))

print(ans)

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

Q = deque([(i, j, 0) for i in range(H) for j in range(W) if A[i][j] == "#"])

ans = 0
while Q:
    i, j, dist = Q.popleft()
    ans = max(ans, dist)
    for di, dj in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
        ni, nj = i + di, j + dj
        if 0 <= ni < H and 0 <= nj < W and A[ni][nj] == ".":
            A[ni][nj] = "#"
            Q.append((ni, nj, dist + 1))

print(ans)

Submission status: Accepted

Solution code:
import scipy.ndimage
import numpy as np

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

data = []

for a in range(h):
  q = raw_input()
  q = q.replace(".","1").replace("#","0")
  data.append( map(int,list(q)) )

A = np.array(data)
x = scipy.ndimage.morphology.distance_transform_cdt(A, metric='taxicab')
#print x
print np.max(x)

Submission status: Accepted

Solution code:
from collections import deque

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

dy = [0,1,0,-1]
dx = [1,0,-1,0]
Field = [[-1]*W for i in range(H)]
for i in range(H):
    for j in range(W):
        if A[i][j] == '#':
            Field[i][j] = 0
            que.append((i, j))

d = 0
while que:
    y,x = que.popleft()
    d = Field[y][x]
    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]
        if not 0 <= nx < W or not 0 <= ny < H or Field[ny][nx] != -1:
            continue
        Field[ny][nx] = d+1
        que.append((ny, nx))
print(d)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
Max = 2000
def l():
    return list(map(int,input().split()))
def m():
    return map(int,input().split())

h,w = m()

aa = [[] for i in range(h)]
aaa = []
ma = 0
for i in range(h):
    k = list(input())
    for j in range(w):
        if k[j] == "#":
            aa[i].append(0)
            aaa.append([i,j])
        else:
            aa[i].append(Max)
kk = []
while True:
    if len(aaa) == 0:
        break
    for i in range(len(aaa)):
        c,v = aaa[i]
        if not c == 0:
            if aa[c-1][v] > aa[c][v]+1:
                aa[c-1][v] = aa[c][v]+1
                kk.append([c-1,v])
                ma = max(ma,aa[c-1][v])
        if not c == h-1:
            if aa[c+1][v] > aa[c][v]+1:
                aa[c+1][v] = aa[c][v]+1
                kk.append([c+1,v])
                ma = max(ma,aa[c+1][v])
        if not v == 0:
            if aa[c][v-1] > aa[c][v]+1:
                aa[c][v-1] = aa[c][v]+1
                kk.append([c,v-1])
                ma = max(ma,aa[c][v-1])
        if not v == w-1:
            if aa[c][v+1] > aa[c][v]+1:
                aa[c][v+1] = aa[c][v]+1
                kk.append([c,v+1])
                ma = max(ma,aa[c][v+1])
    aaa = kk
    kk = []
print(ma)

Submission status: Accepted

Solution code:
import sys


def input():
    return sys.stdin.readline()[:-1]


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

A = [[1 if s == "#" else 0 for s in input()] for i in range(H)]

lu = [[1<<20] * (W+2) for j in range(H + 2)]

for ii in range(H * W):
    i = ii // W + 1
    j = ii % W + 1
    lu[i][j] = min(lu[i - 1][j], lu[i][j - 1]) + 1
    if A[i - 1][j - 1]:
        lu[i][j] = 0
    elif j < W and A[i - 1][j]:
        lu[i][j] = 1

for ii in range(H * W):
    i = H - ii // W
    j = W - ii % W
    lu[i][j] = min(lu[i + 1][j] + 1, lu[i][j + 1] + 1, lu[i][j])

dist = []
[dist.extend(l[1:-1]) for l in lu[1:-1]]
print(max(dist))

Submission status: Accepted

Solution code:


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

m = []
l = []
end = 0
for y in range(H):
    h = list(input())
    m.append(h)
    for x, w in enumerate(h):
        if w == '#':
            l.append([y, x])
            end += 1
HW = H * W
ans = 0
# print(m[2][0]) m[y][x]
while (end < HW):
    nl = []
    for ll in l:
        if (0 < ll[1]):
            if (m[ll[0]][ll[1] - 1] == '.'):
                m[ll[0]][ll[1] - 1] = '#'
                end += 1
                nl.append([ll[0], ll[1] - 1])

        if (ll[1] < W - 1):
            if (m[ll[0]][ll[1] + 1] == '.'):
                m[ll[0]][ll[1] + 1] = '#'
                end += 1
                nl.append([ll[0], ll[1] + 1])

        if (0 < ll[0]):
            if (m[ll[0] - 1][ll[1]] == '.'):
                m[ll[0] - 1][ll[1]] = '#'
                end += 1
                nl.append([ll[0] - 1, ll[1]])

        if (ll[0] < H - 1):
            if (m[ll[0] + 1][ll[1]] == '.'):
                m[ll[0] + 1][ll[1]] = '#'
                end += 1
                nl.append([ll[0] + 1, ll[1]])

    l = nl
    ans += 1

print(ans)

Submission status: Accepted

Solution code:
from collections import deque
H,W = map(int, input().split())
#a = [['#'] * (W+2) for i in range(H+2)]
cnt = [[-5] * (W+2) for i in range(H+2)]
c = 0
fin = 0
st = deque()
sts = deque()
push, pop = st.append, st.pop
pushs, pops = sts.append, sts.pop
for h in range(1,H+1):
    ai = input()
    for w in range(1,W+1):
        #a[h][w] = ai[w-1]
        if ai[w-1] == '#':
            cnt[h][w] = c
            push([h,w])
            fin += 1
        else:
            cnt[h][w] = -1


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

while fin < H*W:
    while st:
        [h,w] = pop()
        for dx,dy in dxy:
            if cnt[h+dx][w+dy] == -1:
                #print(c,fin)
                cnt[h+dx][w+dy] = c+1
                pushs([h+dx,w+dy])
                fin += 1
    c += 1
    while sts:
        [h,w] = pops()
        push([h,w])


print(c)

Submission status: Accepted

Solution code:
h,w= map(int, input().split())
a = []
x = []
for i in range(h):
    li = input()
    aa = []
    for j in range(w):
        aa.append(li[j])
        if aa[j] == '#':
            x.append((i, j))
    a.append(aa)
ans = 0
while True:
    xx = []
    for p in x:
        pp = [(p[0]-1, p[1]), (p[0]+1, p[1]), (p[0], p[1]-1), (p[0], p[1]+1)]
        for ppp in pp:
            if (0 <= ppp[0] < h) and (0 <= ppp[1] < w):
                if a[ppp[0]][ppp[1]] == '.':
                    a[ppp[0]][ppp[1]] = '#'
                    xx.append((ppp[0], ppp[1]))
    x = xx
    if len(x) == 0:
        break
    ans += 1
    # print(x)
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
H, W = map(int, input().split())
maze = [input()for _ in range(H)]


def bfs(queue: deque, reached: set) -> int:
    ans = 0
    dxdy = [[1, 0], [-1, 0], [0, 1], [0, -1]]
    while queue:
        d = queue.pop()
        if ans < d[2]:
            ans = d[2]
        for a in dxdy:
            x = d[0] + a[0]
            y = d[1] + a[1]
            if 0 <= x < W and 0 <= y < H and not reached[y][x]:
                queue.appendleft((x, y, d[2] + 1))
                reached[y][x] = True
    return ans


queue = deque()
reached = [[False for i in range(W)] for j in range(H)]
for i in range(H):
    for j in range(W):
        if maze[i][j] == '#':
            queue.append((j, i, 0))
            reached[i][j] = True
print(bfs(queue, reached))

Submission status: Accepted

Solution code:
from collections import deque
def main():
    h, w = map(int, raw_input().split())
    s = [raw_input().strip() for _ in xrange(h)]
    q = deque()
    po = q.popleft
    pu = q.append
    a = [100000] * (h * w)
    for i, r in enumerate(s):
        for j, c in enumerate(r):
            if c == '#':
                pu((i, j))
                a[i*w+j] = 0
    while q:
        x, y = po()
        z = a[x*w+y] + 1
        if x and a[(x-1)*w+y] > z:
            a[(x-1)*w+y] = z
            pu((x-1,y))
        if x < h - 1 and a[(x+1)*w+y] > z:
            a[(x+1)*w+y] = z
            pu((x+1,y))
        if y and a[x*w+y-1] > z:
            a[x*w+y-1] = z
            pu((x,y-1))
        if y < w - 1 and a[x*w+y+1] > z:
            a[x*w+y+1] = z
            pu((x,y+1))
    print z - 1
main()

Submission status: Accepted

Solution code:
from scipy import ndimage
import numpy as np
import sys
input = sys.stdin.readline

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

A_array = np.array(
    [[0 if s == "#" else 1 for s in input()[:-1]] for i in range(H)])
# print(A_array)


# print(A_array)
b = ndimage.morphology.distance_transform_cdt(
    A_array, metric="taxicab")
print(np.max(b))

Submission status: Accepted

Solution code:
from collections import deque
dx=[1,0,-1,0]
dy=[0,1,0,-1]

h, w = list(map(int, input().split()))
board = [list(input()) for i in range(h)]
q = deque()
for i in range(h):
    for j in range(w):
        if board[i][j] == "#":
            board[i][j] = True
            q.append((i, j, 0))
        else:
            board[i][j] = False

ans = 0
while q:
    i,j,cnt = q.popleft()
    for x, y in zip(dx,dy):
        if 0<=i+x<h and 0<=j+y<w and not board[i+x][j+y]:
            board[i+x][j+y] = True
            q.append((i+x, j+y, cnt+1))
            ans = max(ans, cnt+1)
print(ans)

Submission status: Accepted

Solution code:
from heapq import*
h,w=map(int,input().split())
grid=[["#"]*(w+2)]+[list("#"+input()+"#")for x in range(h)]+[["#"]*(w+2)]

stack=[]
for y in range(1,h+1):
    for x in range(1,w+1):
        if grid[y][x]=="#":
            grid[y][x]=0
            stack.append((y,x))

for i in range(h*w):
    tmp=[]
    for my,mx in stack:
        for y,x in ([0,1],[1,0],[-1,0],[0,-1]):
            if grid[my+y][mx+x]==".":
                grid[my+y][mx+x]=i+1
                tmp.append([my+y,mx+x])
    stack=tmp
    if len(tmp)==0:
        print(i)
        break

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = I()
    return l
def LIR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LI()
    return l
def SR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = S()
    return l
def LSR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LS()
    return l
sys.setrecursionlimit(1000000)
mod = 1000000007

#A
def A():
    h,w = LI()
    a = [sys.stdin.readline() for i in range(h)]
    s = 0
    p = deque()
    M = w*h
    d = [[-1 for i in range(w)] for j in range(h)]
    for i in range(h):
        for j in range(w):
            if a[i][j] == "#":
                p.append((i,j))
                d[i][j] = 0
    move = [[-1,0],[1,0],[0,-1],[0,1]]
    while p:
        y,x = p.popleft()
        for dy,dx in move:
            y2 = y+dy
            x2 = x+dx
            if 0 <= y2 < h and 0 <= x2 < w:
                if d[y2][x2] < 0:
                    d[y2][x2] = d[y][x]+1
                    p.append([y2,x2])
    ans = 0
    for i in d:
        for j in i:
            if j > ans:
                ans = j
    print(ans)
    return

#B
def B():
    h,w,n = LI()
    sy,sx = LI()
    sy -= 1
    sx -= 1
    s = S()
    t = S()
    ks = list("LRUD")
    kt = list("RLDU")
    ds = [[0,-1],[0,1],[-1,0],[1,0]]
    dt = [[0,1],[0,-1],[1,0],[-1,0]]
    for i in range(4):
        y,x = [sy,sx]
        for j in range(n):
            if s[j] == ks[i]:
                y+=ds[i][0]
                x+=ds[i][1]
                if y < 0 or y >= h or x < 0 or x >= w:
                    print("NO")
                    quit()
            if t[j] == kt[i]:
                y += dt[i][0]
                x += dt[i][1]
                if y < 0:y = 0
                elif y >= h:y = h-1
                elif x < 0:x=0
                elif x >= w:x=w-1
    print("YES")
    return

#C
def C():
    def dijkstra(s):
        d = [float("inf") for i in range(n)]
        d[s] = 0
        q=[[0,s]]
        while q:
            dx,x = heappop(q)
            for y in v[x]:
                if dx+1 < d[y]:
                    d[y] = dx+1
                    heappush(q,[d[y],y])
        return d
    n = I()
    v = [[] for i in range(n)]
    for i in range(n-1):
        a,b = LI()
        a -= 1
        b -= 1
        v[a].append(b)
        v[b].append(a)
    d = dijkstra(0)
    l = d.index(max(d))
    d = dijkstra(l)
    m = max(d)+1
    if m%3 == 2:
        print("Second")
    else:
        print("First")
    return

#D
def D():
    n = I()
    return

#E
def E():
    n = I()
    return

#F
def F():
    n = I()
    return

#Solve
if __name__ == "__main__":
    A()

Submission status: Accepted

Solution code:
from collections import*
h,w=map(int,input().split())
c=eval('list(input()),'*h)
q=deque()
e=q.append
for i in range(h):
 for j in range(w):
  if'.'>c[i][j]:e((i,j,0))
a=0
while q:
 y,x,v=q.popleft();a=max(a,v)
 for i,j in((y,x-1),(y,x+1),(y-1,x),(y+1,x)):
  if h>i>=0and w>j>=0and'#'<c[i][j]:c[i][j]='#';e((i,j,v+1))
print(a)