Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

def solve():
    H, W = map(int, input().split())
    mass = [[0] * W for _ in range(H)]
    for Hi in range(H):
        massHi = [0 if s == '.' else 1 for s in list(input())]
        for Wi in range(W):
            mass[Hi][Wi] = massHi[Wi]

    # import pprint
    # pprint.pprint(mass)

    result = 0
    for Hi in range(H):
        for Wi in range(W):
            if mass[Hi][Wi] == 1:
                break
            sub_result = 100000000
            for Hi2 in range(H):
                for Wi2 in range(W):
                    if mass[Hi2][Wi2] == 1:
                        sub_result = min(sub_result,
                                         abs(Hi2 - Hi) + abs(Wi2 - Wi))
            result = max(result, sub_result)
    print(result)


if __name__ == '__main__':
    solve()


### FIXED CODE ###

"""
解説と提出 #5747380を参考に作成
"""

from collections import deque


def solve():
    H, W = map(int, input().split())
    # mass = [[False] * W for _ in range(H)]
    # queue1 = deque([])
    # queue2 = deque([])
    queue1 = []
    queue2 = []
    mass = []
    mass.append([False] * (W + 2))  # 外枠
    for Hi in range(1, H + 1):
        mass.append([False] + [s == '.' for s in list(input())] + [False])
        for Wi in range(1, W + 1):
            if not mass[Hi][Wi]:
                queue1.append((Hi, Wi))
    mass.append([False] * (W + 2))  # 外枠
    import datetime
    d = datetime.datetime.now()
    count = -1
    while True:
        # print('count: {}, queue:{}'.format(count, len(queue1)))
        if len(queue1) == 0:
            break
        for h, w in queue1:
            # left
            if mass[h][w - 1]:
                mass[h][w - 1] = False
                queue2.append((h, w - 1))
            # right
            if mass[h][w + 1]:
                mass[h][w + 1] = False
                queue2.append((h, w + 1))
            # top
            if mass[h + 1][w]:
                mass[h + 1][w] = False
                queue2.append((h + 1, w))
            # button
            if mass[h - 1][w]:
                mass[h - 1][w] = False
                queue2.append((h - 1, w))

        count += 1
        queue1 = queue2
        queue2 = []
    print(count)

    # print(datetime.datetime.now() - d)


if __name__ == '__main__':
    solve()
### BUGGY CODE ###

N,Q=map(int,input().split())
S=input()
LR=[list(map(int,input().split())) for i in range(Q)]
I=[]
for i in range(N-1):
  if S[i:i+2]=="AC":
    I.append(i)
for i in range(Q):
  l=LR[i][0]-1
  r=LR[i][1]-1
  ans=0
  for j in range(len(I)):
    if l<=I[j] and I[j]+1<=r:
        ans+=1
    if r<I[j]:
      break
  print(ans)

### FIXED CODE ###

N,Q=map(int,input().split())
S=input()
LR=[list(map(int,input().split())) for i in range(Q)]
I = [0 for i in range(N)]
for i in range(N-1):
  if S[i]=="A" and S[i+1]=="C":
    I[i+1]=I[i]+1
  else:
    I[i+1]=I[i]
      
for i in range(Q):
  l=LR[i][0]-1
  r=LR[i][1]-1
  print(I[r]-I[l])
### BUGGY CODE ###

n = int(input())
A = [int(num) for num in input().split()]

cont = False
if n % 2 == 1:
  if A.count(0) != 1:
    cont = True
  else:
    for i in range(2, n, 2):
      if A.count(i) != 2:
        cont = True
        break
else:
  for i in range(1, n, 2):
    if A.count(i) != 2:
      cont = True
      break

if cont == True:
  print(0)
else:
  print(2**(n//2) % (10**9 + 7))

### FIXED CODE ###

n = int(input())
A = [int(num) for num in input().split()]
import collections as cl
dic = cl.Counter(A)

cont = False
if n % 2 == 1:
  if dic[0] != 1:
    cont = True
  else:
    dic[0] = 2
    for num in dic.values():
      if num != 2:
        cont = True
        break
else:
  for num in dic.values():
    if num != 2:
      cont = True
      break

if cont == True:
  print(0)
else:
  print(2**(n//2) % (10**9 + 7))
### BUGGY CODE ###

N = int(input())
A = list(map(int,input().split()))
l = []
n = 0
for i in range(1,N):
    n += A[i]*sum(A[:i])

print(n%(10**9+7))

### FIXED CODE ###

N = int(input())
A = list(map(int,input().split()))
B = sum(A)
new_A = A.reverse()
n = 0
for i in range(N-1):
    n += A[i]*(B-A[i])
    B = B-A[i]

print(n%(10**9+7))
### BUGGY CODE ###

#!/usr/bin/env python3
# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys
import collections
from decimal import Decimal # 10進数で考慮できる

mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000

d = collections.deque()
def LI(): return list(map(int, sys.stdin.readline().split()))

N = int(input())
A = LI()

"""
pairwise coprime 1,3,7,10
setwise coprime 2,3,4,10


coprimeかどうかで全部やる
"""

def primes(n): #試し割り法で各素因数とその指数を求める
    cnt=collections.defaultdict(int)
    for i in range(2,int(n**0.5)+1):
        if n%i==0:
            while n%i==0:
                cnt[i]+=1
                n//=i
    if n!=1:
        cnt[n]+=1
    return cnt


def solve():
    gcd = A[0]
    for a in A:
        gcd = math.gcd(gcd, a)
    if gcd != 1:
        return "not coprime"

    history = {}
    for i in range(10**6):
        history[i] = 0

    for a in A:
        d = primes(a)
        for key in d.keys():
            history[key] += 1
            if history[key] > 1:
                return "setwise coprime"
    return "pairwise coprime"
 
    
print(solve())

### FIXED CODE ###

#!/usr/bin/env python3
# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys
import collections
from decimal import Decimal # 10進数で考慮できる

mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000

d = collections.deque()
def LI(): return list(map(int, sys.stdin.readline().split()))

N = int(input())
A = LI()

"""
pairwise coprime 1,3,7,10
setwise coprime 2,3,4,10


coprimeかどうかで全部やる
"""

def primes(n): #試し割り法で各素因数とその指数を求める
    cnt=collections.defaultdict(int)
    for i in range(2,int(n**0.5)+1):
        if n%i==0:
            while n%i==0:
                cnt[i]+=1
                n//=i
    if n!=1:
        cnt[n]+=1
    return cnt


def solve():
    gcd = A[0]
    for a in A:
        gcd = math.gcd(gcd, a)
    if gcd != 1:
        return "not coprime"

    history = {}
    for i in range(10**6):
        history[i] = 0

    for a in A:
        d = primes(a)
        for key in d.keys():
            history[key] += 1
            if history[key] > 1:
                return "setwise coprime"
    return "pairwise coprime"
 
    
print(solve())
### BUGGY CODE ###

N,M = list(map(int,input().split()))
A = list(map(int,input().split()))
for i in range(M):
    A.sort()
    A[len(A)-1] = A[len(A)-1] // 2
print(sum(A))

### FIXED CODE ###

import heapq
N,M = map(int, input().split())
A = list(map(lambda x: -int(x), input().split()))
heapq.heapify(A)
ans = 0
for i in range(M):
    most_expensive = -heapq.heappop(A)
    most_expensive //= 2
    heapq.heappush(A, -most_expensive)
print(-sum(A))
### BUGGY CODE ###

from collections import Counter
def prime_factorize(n):
    a = []
    while n % 2 == 0:
        a.append(2)
        n //= 2
    f = 3
    while f * f <= n:
        if n % f == 0:
            a.append(f)
            n //= f
        else:
            f += 2
    if n != 1:
        a.append(n)
    return a
def factorize(m):
    d = []
    for i in range(1, int(m**0.5)+1):
        if m % i == 0:
            d.append(i)
            if i != m // i:
                d.append(m//i)
    return d
def main():
    N = int(input())
    A = list(map(int, input().split()))
    l = []
    for i in A:
        l.extend(factorize(i))
    c = Counter(l)
    m = 1
    for k in c:
        if c[k] >= N-1 and k > m:
            m = k
    print(m)
main()


### FIXED CODE ###

from collections import OrderedDict
def prime_factorize(n):
    a = []
    while n % 2 == 0:
        a.append(2)
        n //= 2
    f = 3
    while f * f <= n:
        if n % f == 0:
            a.append(f)
            n //= f
        else:
            f += 2
    if n != 1:
        a.append(n)
    return a
def factorize(m):
    d = []
    for i in range(1, int(m**0.5)+1):
        if m % i == 0:
            d.append(i)
            if i != m // i:
                d.append(m//i)
    return d
def main():
    N = int(input())
    A = list(map(int, input().split()))
    l = list(set(factorize(A[0]) + factorize(A[1])))
    l.sort(reverse=True)
    d = OrderedDict()
    for i in l:
    	d[i] = 0
    for i in A:
        for j in d:
            if i % j == 0:
                d[j] += 1
    m = 1
    for k in d:
        if d[k] >= N-1:
            print(k)
            return
    print(1)
main()
### BUGGY CODE ###

n = int(input())
s = input()

lst = [set([]), set([s[0]])]
ans = 0
for end in range(2, n+1):
    new_set = set([])
    for start in range(end):
        if s[start:end] in lst[start]:
            ans = max(ans, len(s[start:end]))
        new_set.add(s[start:end])
    new_set = new_set | lst[-1]
    lst.append(new_set)
print(ans)

### FIXED CODE ###

def z_algorithm(s):
    n = len(s)
    z = [0 for i in range(n)]
    z[0] = n
    i, j = 1, 0
    while i < n:
        while i+j < n and s[j] == s[i+j]:
            j += 1
        z[i] = j
        if j == 0:
            i += 1
            continue
        k = 1
        while k < j and k + z[k] < j:
            z[i+k] = z[k]
            k += 1
        i += k
        j -= k
    return z

n = int(input())
s = input()

ans = 0
for i in range(n):
    z = z_algorithm(s[i:])
    for j in range(len(z)):
        if z[j] <= j:
            ans = max(ans, z[j])
print(ans)
### BUGGY CODE ###

S = input()
s_rev = S[::-1]

r_list = [0] * 2019
r_list[0] = 1
m = len(S)
num = 0
for i in range(len(S)):
    num += (10**i)*int(s_rev[i])
    r_list[num % 2019] += 1

ans = 0
for i in range(2019):
        ans += r_list[i]*(r_list[i]-1)//2

print(ans)


### FIXED CODE ###

S = input()
s_rev = S[::-1]

r_list = [0] * 2019
r_list[0] = 1
num, d = 0, 1
for i in range(len(S)):
    num += d*int(s_rev[i])
    num %= 2019
    r_list[num] += 1
    d *= 10
    d %= 2019

ans = 0
for i in range(2019):
        ans += r_list[i]*(r_list[i]-1)//2

print(ans)
### BUGGY CODE ###

n, k = map(int, input().split())
H = list(map(int, input().split()))
dp = [float("inf") for _ in range(n)]  # 最小化問題なのでinfで初期化
dp[0] = 0  # 初期条件
 
dp[1] = dp[0] + abs(H[1] - H[0])  # 初期条件2
 
for i in range(n - 1):  # 配るDP
    for j in  range(1, min(k+1, n-i)):
        dp[i + j] = min(dp[i + j], dp[i] + abs(H[i + j] - H[i]))
print(dp[n - 1])

### FIXED CODE ###

N, K = map(int, input().split())
*h, = map(int, input().split())
dp = [float("inf") for _ in range(N)]
dp[0] = 0
for i in range(N - 1):
	for j in range(1, min(K + 1, N - i)):
		dp[i + j] = min(dp[i + j], dp[i] + abs(h[i + j] - h[i]))
print(dp[N - 1])
### BUGGY CODE ###

#Replacing
import numpy as np
N = int(input())
A = np.array(sorted(map(int, input().split())))
Q = int(input())
u, count = np.unique(A,return_counts=True)
asum = A.sum()
for i in range(Q):
    B, C = list(map(int, input().split()))
    asum += count[u==B].sum() * (C-B)
    u = np.where(u==B,C,u)
    print(asum)

### FIXED CODE ###

#Replacing
import numpy as np
N = int(input())
A = np.array(list(map(int, input().split())))
Q = int(input())
u, count = np.unique(A,return_counts=True)
L = np.zeros(10**5,int)
for i in range(len(u)):
    L[u[i]-1] = count[i]
asum = A.sum()
for i in range(Q):
    B, C = list(map(int, input().split()))
    asum += L[B-1] * (C-B)
    L[C-1] += L[B-1]
    L[B-1] = 0
    print(asum)
### BUGGY CODE ###

n = int(input())
x = [0] + [int(input()) for i in range(n)]
cnt = 1
idx = min(x[1:])
while True:
    if x[idx] == 2:
        ans = cnt
        break
    elif x.index(x[idx]) == x.index(min(x[1:])):
        ans = -1
        break
    idx = x[idx]
    cnt += 1
print(ans)

### FIXED CODE ###

def train(n):
    x =[0] + [int(input()) for i in range(n)]
    idx = 1
    for i in range(n+1):
        if x[idx] == 2:
            return i + 1
        idx = x[idx]
    return -1
n = int(input())
print(train(n))
### BUGGY CODE ###

#import numpy as np
import heapq
import sys
sys.setrecursionlimit(10**6)

H,W = map(int,input().split())
INF = 10**18
q = []

#d = np.full((H,W),INF,dtype=np.int64) # '#'からの距離
d = [[INF]*W for _ in range(H)]

for i in range(H):
  txt = input()
  for j,c in enumerate(txt):
    if c == '#':
      d[i][j] = 0
      heapq.heappush(q,(0,i,j))

ans = 0

while q:
  dv,x,y = heapq.heappop(q)
  ans = dv
  for dx,dy in [(0,1),(0,-1),(1,0),(-1,0)]:
    xx = x+dx
    yy = y+dy
    if xx == -1 or xx == H:
      continue
    if yy == -1 or yy == W:
      continue
    if d[xx][yy] == INF:
      d[xx][yy] = dv+1
      heapq.heappush(q,(dv+1,xx,yy))

print(ans)

### FIXED CODE ###

import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline

H,W = map(int,input().split())
INF = 10**18
q = []

visited = [[True]*(W+2)]
visited += [[True] + [x == '#' for x in input().rstrip()] + [True] for _ in range(H)]
visited.append([True]*(W+2))
  
for i in range(1,H+1):
  for j in range(1,W+1):
    if visited[i][j]:
      q.append((i,j))

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

ans = -1
while q:
  qq = []
  ans += 1
  for x,y in q:
    if not visited[x-1][y]:
      visited[x-1][y] = True
      qq.append((x-1,y))
    if not visited[x+1][y]:
      visited[x+1][y] = True
      qq.append((x+1,y))
    if not visited[x][y-1]:
      visited[x][y-1] = True
      qq.append((x,y-1))
    if not visited[x][y+1]:
      visited[x][y+1] = True
      qq.append((x,y+1))
  q = qq
  
print(ans)
### BUGGY CODE ###



import numpy as np
N,K=map(int,input().split())
A=list(map(int,input().split()))

A=np.array(A)

A_pos=np.sort(A[A>0])
A_neg=np.sort(A[A<0])
A_neg2=np.sort(-A_neg)

np=len(A_pos)
nn=len(A_neg)
nz=N-np-nn
n_post=np*(np-1)//2+(nn*(nn-1))//2
n_zero=nz*(np+nn)+nz*(nz-1)//2
n_neg=np*nn



#array内で積がx未満になるペアの数
def syakutori_pos1(x):
    res=0
    j=np-1
    y1=-(-x//A_pos)
    for i in range(np):
        tmp=0
#         j=n-1

        while j!=-1:
            
            if A_pos[j]>=y1[i]:
                j-=1
            else:
                break
        
        tmp+=j+1
        if A_pos[i]**2<x:
            tmp-=1

        res+=tmp
    res=res//2
    return res


def syakutori_pos2(x):
    res=0
    j=nn-1
    y2=-(-x//A_neg2)
    for i in range(nn):
        tmp=0
#         j=n-1

        while j!=-1:
            
            if A_neg2[j]>=y2[i]:
                j-=1
            else:
                break
        
        tmp+=j+1
        if A_neg2[i]**2<x:
            tmp-=1

        res+=tmp
    res=res//2
    return res


#array内で積がx未満になるペアの数

def syakutori_neg(x):
    yn=x//A_neg
#     print(A_pos,y)
    res=0
    i=0
    j=np-1
    for z in reversed(yn):
        while(j!=-1):
            if z<A_pos[j]:
                j-=1
            else:
                break
#         print(z,j+1)
        res+=j+1
    return np*nn-res



def syakutori(x):
    if x>0:
        return syakutori_pos1(x)+syakutori_pos2(x)+n_neg+n_zero
    elif x==0:
        return n_neg
    else:
        return syakutori_neg(x)




r=10**18
l=-10**18
while(r-l>1):
    mid=(l+r)//2
    z=syakutori(mid)
#     z= count_pair(mid)
#     print(l,r)
    if z < K:
        l=mid
    else:
        r=mid
print(l)

### FIXED CODE ###

import numpy as np
N,K=map(int,input().split())
A=list(map(int,input().split()))

A=np.array(A)

A_pos=np.sort(A[A>0])
A_neg=np.sort(A[A<0])
A_neg2=-A_neg[::-1]
n_pos=len(A_pos)
n_neg=len(A_neg)
n_zero=N-n_pos-n_neg

def position_in_neg(x):
    y=n_pos-np.searchsorted(A_pos,x//A_neg,side='right')
    return y.sum()

def position_in_pos(x):
    z=np.searchsorted(A_pos,-(-x//A_pos),side='left')
    w=np.searchsorted(A_neg2,-(-x//A_neg2),side='left')
    tmp=len(A_pos[A_pos**2<x])+len(A_neg2[A_neg2**2<x])
    return (z.sum()+w.sum()-tmp)//2

def position(x):
    if x<0:
        return position_in_neg(x)
    elif x==0:
        return n_pos*n_neg
    else:
        return position_in_pos(x)+n_pos*n_neg+(n_pos+n_neg)*n_zero+n_zero*(n_zero-1)//2

l=-pow(10,18)
r=pow(10,18)
while(r-l>1):
    mid=(l+r)//2
    if position(mid)<K:
        l=mid
    else:
        r=mid
print(l)
### BUGGY CODE ###

import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from collections import defaultdict
def main():
    n = int(input())
    if n == 1:
        print(1)
        sys.exit()
    # 1からｎまでの数それぞれの約数を求める。約数の側から倍数になっているか数える。
    nums = [2] * (n + 1) # 1～nの約数をいれる器。「1とその数自身」があるので初期値2．
    nums[1] = 1 # 1の約数は１だけなので初期値１。
    for i1 in range(2, n // 2 + 1):
        for i2 in range(i1 * 2, n + 1, i1): # i1～nのあいだを間隔i1でスキップしていく。
            nums[i2] += 1
    r = 1 # 数１のk * f(k)は１なので初期値に１にする。
    for j1 in range(2, n + 1):
        r += j1 * nums[j1]
    print(r)

if __name__ == '__main__':
    main()

### FIXED CODE ###

import sys
read = sys.stdin.read
from math import sqrt, floor
def main():
    n = int(input())
    if n == 1:
        print(1)
        sys.exit()
    # nd:num of div
    nd = [2] * (n + 1)

    for i1 in range(2, floor(n / 2) + 1):
        for i2 in range(i1 * 2, n + 1, i1):
            nd[i2] += 1

    r = 1
    for j1 in range(2, n + 1):
        r += nd[j1] * j1
    print(r)

if __name__ == '__main__':
    main()
### BUGGY CODE ###

from collections import deque

n, x, y = [int(x) for x in input().split()]
x -= 1
y -= 1
BIG = 65521
ans = [0] * n

# deque の代わりにタプルを使い捨てにしてみる。
# quが未定義だと言われる，なんで，グローバルじゃないの？
# じゃない。nonlocal宣言で解決した。


def bfs(start_v):
    """ある始点からほかの全点に行くまでの最短距離を求める。"""
    qu = (start_v,)
    # 始点からvに移動するまでの最短距離: dist[v]
    dist = [BIG] * n

    def push(v, d):
        """始点からvまでの最短距離が算出されていないときに，その距離を保存し，
        キューに頂点vを追加する。"""
        nonlocal qu
        if dist[v] != BIG:
            # 既に訪問済みで距離が求められている。
            return
        dist[v] = d
        qu = qu + (v,)

    push(start_v, 0)

    while len(qu):
        v = qu[0]
        qu = qu[1:]
        # 始点からvの次の頂点へ移動する距離。
        d = dist[v] + 1
        if v < n - 1:
            push(v + 1, d)
        if v > 0:
            push(v - 1, d)
        if v == x:
            push(y, d)
        if v == y:
            push(x, d)

    for i in range(n):
        ans[dist[i]] += 1


def main():
    for i in range(n):
        bfs(i)

    for i in range(1, n):
        print(ans[i] // 2)


if __name__ == '__main__':
    main()


### FIXED CODE ###

from collections import deque

n, x, y = [int(x) for x in input().split()]
x -= 1
y -= 1
BIG = 65521
ans = {i: 0 for i in range(n)}


def bfs(start_v):
    """ある始点からほかの全点に行くまでの最短距離を求める。"""
    qu = deque()
    qu_append = qu.append
    qu_popleft = qu.popleft
    qu_append(start_v)
    # 始点からvに移動するまでの最短距離: dist[v]
    dist = [BIG] * n

    def push(v, d):
        """始点からvまでの最短距離が算出されていないときに，その距離を保存し，
        キューに頂点vを追加する。"""
        if dist[v] != BIG:
            # 既に訪問済みで距離が求められている。
            return
        dist[v] = d
        qu_append(v)

    push(start_v, 0)

    while len(qu):
        v = qu_popleft()
        # 始点からvの次の頂点へ移動する距離。
        d = dist[v] + 1
        if v < n - 1:
            push(v + 1, d)
        if v > 0:
            push(v - 1, d)
        if v == x:
            push(y, d)
        if v == y:
            push(x, d)

    for i in range(n):
        if dist[i] != 0:
            ans[dist[i]] += 1


def main():
    for i in range(n):
        bfs(i)

    for i in range(1, n):
        print(ans[i] // 2)


if __name__ == '__main__':
    main()

# TLE
### BUGGY CODE ###

n = int(input())
a = list(map(int, input().split()))
res = []
if n % 2 == 0:
  for i in range(n):
    if i % 2 == 0:
      res.append(a[i])
    else:
      res.insert(0,a[i])
  print(*res)
else:
  for i in range(n):
    if i % 2 == 0:
      res.insert(0,a[i])
    else:
      res.append(a[i])
  print(*res)

### FIXED CODE ###

n = int(input())
a = list(map(int, input().split()))
res1 = []
res2 = []
if n % 2 == 1:
  res1.append(a.pop(-1))
  n = n -1
  for i in range(n//2):
    res1.append(a[n-2-2*i])
    res2.append(a[1+i*2])
  res1.extend(res2)
  print(*res1)
else:
  for i in range(n//2):
    res1.append(a[n-1-2*i])
    res2.append(a[i*2])
  res1.extend(res2)
  print(*res1)
### BUGGY CODE ###

# -*- coding: utf-8 -*-
n, k = map(int, input().split())
h = list(map(int, input().split()))

INF = float('inf')
dp = [INF for _ in range(n)]
dp[0] = 0

for i in range(1, n):
    l, r = max(i - k, 0), i
    dp[r] = min([dp[j] + abs(h[r] - h[j]) for j in range(l, r)])

print(dp[-1])

### FIXED CODE ###

# -*- coding: utf-8 -*-
n, k = map(int, input().split())
h = list(map(int, input().split()))

INF = float('inf')
dp = [INF for _ in range(n)]
dp[0] = 0

for i in range(1, n):
    l, r = max(i - k, 0), i
    dp[i] = min([pdp + abs(h[i] - ph) for pdp, ph in zip(dp[l:r], h[l:r])])

print(dp[-1])
### BUGGY CODE ###

#!/usr/bin/env python3
import sys
sys.setrecursionlimit(1000000)
from collections import deque

H, W = map(int, input().split())
#配列の入力
data = [list(input()) for _ in range(H)]

memo = [[-1 for _ in range(W)]for _ in range(H)]
que = deque()

for h in range(H):
    for w in range(W):
        if data[h][w] == '#':
            memo[h][w] = 0
            que.append((h, w))

offset = ((-1, 0), (1, 0), (0, -1), (0, 1))
ans = 0
while que:
    now_h, now_w = que.popleft()
    for nh, nw in offset:
        if now_h+nh < 0 or H-1 < now_h+nh or now_w+nw < 0 or W-1 < now_w+nw:
            continue

        if memo[now_h+nh][now_w+nw] >= 0:
            continue

        memo[now_h+nh][now_w+nw] = memo[now_h][now_w]+1
        ans = max(ans, memo[now_h+nh][now_w+nw])
        que.append((now_h+nh,now_w+nw))

print(ans)


### FIXED CODE ###


import sys
sys.setrecursionlimit(1000000)
from collections import deque

H, W = map(int, input().split())
#配列の入力
data = [list(input()) for _ in range(H)]

memo = [[-1 for _ in range(W)]for _ in range(H)]
que = deque()

for h in range(H):
    for w in range(W):
        if data[h][w] == '#':
            memo[h][w] = 0
            que.append((h, w))

offset = ((-1, 0), (1, 0), (0, -1), (0, 1))
while que:
    now_h, now_w = que.popleft()
    for nh, nw in offset:
        if now_h+nh < 0 or H-1 < now_h+nh or now_w+nw < 0 or W-1 < now_w+nw:
            continue

        if memo[now_h+nh][now_w+nw] >= 0:
            continue

        memo[now_h+nh][now_w+nw] = memo[now_h][now_w]+1
        que.append((now_h+nh,now_w+nw))


ans = -1
for h in range(H):
    ans = max(ans, max(memo[h]))
print(ans)
### BUGGY CODE ###

n = int(input())
A = list(map(int, input().split()))
cnt = 1
idx = 0
if 1 in A:
    while idx > -1:
        if cnt in A:
            idx = A.index(cnt)
            A = A[idx:]
            cnt += 1
        else:
            idx = -1
    print(n - cnt + 1)
else:
    print(-1)

### FIXED CODE ###

n = int(input())
A = list(map(int, input().split()))
cnt = 1
for i in A:
    if i == cnt:
        cnt += 1
if cnt == 1:
    print(-1)
else:
    print(n - cnt + 1)