for Y in R(y,N(b[0])):yield[(u,i)for u in R(x,X+1)for i in R(y,Y+1)]
def r(b):
S={(x,y)for x,j in E(b)for y,_ in E(j)if F!=_};W={*S}
while S:
x,y=[(x,y)for x,y in S if A<b[x][y]][0];Z=(x,y);S-={Z};d,s={x:[y]},[Z];V=b[x][y];q=[Z]
while q:
x,y=q.pop(0)
for X,Y in M:
if(Z:=(J:=x+X,K:=y+Y))in S and b[J][K]in A+V:q+=Z,;S-={Z};d={**d,J:sorted(d.get(J,[])+[K])};s=s+[Z]
ifall(b==d[min(d)]for b in d.values()):yield s
def Z(B,s):
B=eval(str(B))
for x,y in s:B[x][y]=A
return B
def f(b):
q,S=[(b,0)],[(0,b)];L=[i for i in D(b)if i];W=-1
while q:
B,c=q.pop()
if~-any({*i}-{A,F}for i in B):W=[min(W,c),c][W<0];continue
H=[*r(B)];V=lambda U:(2+c>W>=0)<all(C>c for C,u in S if u==U)
for i in H:
if V(U:=Z(B,i)):
q+=(U,c+1),;S+=(c,U),
if N({sum(A<B[x][y]for x,y in j)for j in H})==1:break
if V(U:=Z(B,max([i for i in L if N(T:={B[x][y]for x,y in i})-3<(F in T)<(N(T)==1or A in T)and A!=T],key=lambda X:sum(F!=B[x][y]>A for x,y in X)))):q+=(U,c+1),;S+=(c,U),
return W
s1 ="""
1 1 1 1
1 2 2 2
1 2 3 3
1 2 3 4
1 2 3 4
"""
s2 ="""
1 1 2 2
1 1 2 2
3 3 1 3
"""
s3 ="""
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
"""
s4 ="""
3 3 3 3 3 3
3 2 2 2 2 3
3 2 1 1 2 3
3 2 1 1 2 3
3 2 2 2 2 3
3 3 3 3 3 3
"""
s5 ="""
1 1 1 1 1 1
1 2 2 2 2 1
1 2 0 0 2 1
1 2 0 0 2 1
1 2 2 2 2 1
1 1 1 1 1 1
"""
s6 ="""
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
"""
s7 ="""
1 1 1 1
1 3 3 1
2 3 3 2
2 2 2 4
"""
def to_board(s):
return[i.split()for i infilter(None, s.split('\n'))]