fork download
  1. R=range
  2. def f(x,y,v):
  3. d={}
  4. for j in R(x*y):d[r]=d.get(r:=v.get(z:=(j//y,j%y),-1),[])+[z]
  5. if any(i+1and len(d[i])-2for i in d):return 0
  6. D=eval(str(d));M=max(d);del D[M][0];q=[(M,D,d[M][0],0)]
  7. while q:
  8. M,D,(j,k),C=q.pop(0)
  9. if(j,k)in D[M]:
  10. Y=eval(str(D));del Y[M];M=max(Y)
  11. if~M:q+=(M,Y,Y[M][0],0),;del Y[M][0]
  12. if{-1:[]}==Y:return 1
  13. else:
  14. for T in[(j-1,k),(j+1,k),(j,k+1),(j,k-1)]:
  15. if T in D[-1]:Y=eval(str(D));Y[-1].remove(T);q+=(M,Y,T,C+1),
  16. elif T in D[M]and C:q+=(M,D,T,C+1),
  17.  
  18. s1 = '5,5 0,0,0 3,0,1 1,1,2 1,2,2 4,2,1 4,4,0'
  19. s2 = '5,2 2,0,1 0,1,2 4,1,2'
  20. s3 = '4,2 0,0,0 3,0,0 0,1,0 3,1,0'
  21. s4 = '8,6 0,0,1 7,5,1'
  22. s5 = '2,5 0,0,1 2,0,6 4,0,6 0,1,4 3,1,4 4,1,1'
  23. s6 = '6,3 1,0,4 5,0,1 0,1,4 1,1,3 5,1,3 0,2,2 3,2,2 5,2,1'
  24. s7 = '5,2 0,0,1 3,0,1 0,1,3 4,1,1'
  25. s8 = '2,2 0,0,0 1,1,0'
  26. s9 = '5,5 0,3,0 0,4,1 1,2,2 1,3,1 2,0,0 3,0,4 3,1,2 3,3,5 3,4,4 4,4,5'
  27. s10 = '13,13 1,1,0 9,1,1 10,1,2 11,1,3 1,2,4 2,2,5 5,2,6 7,2,7 3,3,0 5,4,6 6,4,1 9,6,3 4,7,8 5,8,9 12,8,8 11,9,10 2,10,4 4,10,2 9,10,5 11,10,7 1,11,9 12,12,10'
  28. s11 = '7,7 0,0,0 0,1,1 1,1,2 2,1,3 4,2,4 0,3,1 5,3,3 0,4,4 2,4,5 5,4,2 0,5,0 1,5,5 3,5,6 3,7,6'
  29. def to_inp(s):
  30. a, *b = s.split()
  31. return int(a.split(',')[1]),int(a.split(',')[0]), {(int(b),int(a)):int(c)for a, b, c in [i.split(',')for i in b]}
  32.  
  33.  
  34. print(f(*to_inp(s1)))
  35. print(f(*to_inp(s2)))
  36. print(f(*to_inp(s3)))
  37. #print(f(*to_inp(s4))) times out
  38. print(f(*to_inp(s5)))
  39. print(f(*to_inp(s6)))
  40. print(f(*to_inp(s7)))
  41. print(f(*to_inp(s8)))
  42. print(f(*to_inp(s9)))
  43. #print(f(*to_inp(s10))) #times out
  44. print(f(*to_inp(s11)))
Success #stdin #stdout 0.8s 14080KB
stdin
Standard input is empty
stdout
1
0
0
0
None
0
None
1
0