fork download
  1. B=enumerate
  2. O=(0,1),(0,-1),(1,0),(-1,0)
  3. C=lambda b:[(x,r,y,v)for x,r in B(b)for y,v in B(r)]
  4. H=list.count
  5. def I(b,x,y,s):
  6. b=eval(str(b));b[x][y]=0
  7. if b in s:return
  8. t=[(x,y)for x,_,y,v in C(b)if v];q=[t.pop()]
  9. while q:
  10. x,y=q.pop(0)
  11. for T,H in O:
  12. if(E:=(x+T,y+H))in t:q+=E,;t.remove(E)
  13. if[]==t:return b
  14. def f(b):
  15. q,*s=[b],
  16. while q:
  17. b,R=q.pop(0),1
  18. for x,r,y,v in C(b):
  19. if v and(H(r,v)>1or H([*[*zip(*b)][y]],v)>1)and(R:=0)<all(b[x+T][y+H]for T,H in O if len(b)>x+T>-1<y+H<len(r))and(K:=I(b,x,y,s)):q+=K,;s+=K,
  20. if R:return b
  21.  
  22. s1 = '''
  23. 2 2 2 4
  24. 1 4 2 3
  25. 2 3 2 1
  26. 3 4 1 2
  27. '''
  28. s2 = '''
  29. 4 2 4 3
  30. 4 1 1 2
  31. 3 1 2 1
  32. 4 3 1 3
  33. '''
  34. s3 = '''
  35. 1 5 3 1 2
  36. 5 4 1 3 4
  37. 3 4 3 1 5
  38. 4 4 2 3 3
  39. 2 1 5 4 4
  40. '''
  41. def to_board(o_b):
  42. return [[*map(int, i.split())]for i in filter(None, o_b.split('\n'))]
  43.  
  44. print(f(to_board(s1)))
  45. print(f(to_board(s2)))
  46. print(f(to_board(s3)))
Success #stdin #stdout 1.68s 14200KB
stdin
Standard input is empty
stdout
[[0, 2, 0, 4], [1, 4, 2, 3], [2, 3, 0, 1], [3, 0, 1, 2]]
[[0, 2, 4, 3], [4, 1, 0, 2], [3, 0, 2, 1], [0, 3, 1, 0]]
[[1, 5, 3, 0, 2], [5, 0, 1, 3, 4], [3, 4, 0, 1, 5], [4, 0, 2, 0, 3], [2, 1, 5, 4, 0]]