fork download
  1. E=enumerate
  2. L=len
  3. def f(b):
  4. q,F=[{(x,y):v for x,r in E(b)for y,v in E(r)}],[]
  5. for d in q:
  6. O={}
  7. for i in d:
  8. if~-(d[i]in'oO0 '):O[d[i]]=O.get(d[i],[])+[i]
  9. if{}==O:return L(F+[i for i in d if d[i]in'oO0'])
  10. Q,S,W=[[i]for i in O[[*O][0]]],[],[]
  11. for p in Q:
  12. for X,Y in(0,1),(1,0),(-1,0),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1):
  13. if d.get(V:=(p[-1][0]+X,p[-1][1]+Y))in[d[p[0]],' ']:
  14. if V==p[0]and L(p)>2:W+=p,
  15. elif(V in p)<1-((G:=sorted(Z:=p+[V]))in S):Q+=Z,;S+=G,
  16. if W:
  17. Q,T=[(W,[])],[]
  18. for w,P in Q:
  19. for i,j in E(w):C=P+[j];z=sum(map(L,l:=[{i for i in j if' '!=d[i]}for j in C]))==L({j for k in l for j in k});T+=z*[C];Q+=z*[(w[:i]+w[i+1:],C)]
  20. F+=max(T or W,key=L)
  21. for u in O[[*O][0]]:del d[u]
  22. q+=d,
  23.  
  24. def to_grid(s):
  25. return [[*i] for i in filter(None, s.split('\n'))]
  26.  
  27. s1 = """
  28. AAAw
  29. AxA4
  30. 'AoQ
  31. """
  32. s2 = """
  33. 1822uaslkoo
  34. 12*2sl ljoo
  35. a* 0a91)j$*
  36. ()*#J9dddj*
  37. *Q#ID dJj!"
  38. *UJD SO&*93
  39. """
  40. s3 = """
  41. 3 3
  42. 2
  43. """
  44. s4 = """
  45. AAAA
  46. AAAA
  47. AAxA
  48. """
  49. s5 = """
  50. 0QoO
  51. """
  52. s6 = """
  53. W w
  54. Ww
  55. """
  56. s7 = """
  57. W W
  58. WW
  59. """
  60. s8 = """
  61. abcdQefg
  62. hQiQjQQk
  63. QlQmnopQ
  64. QqrstQQu
  65. QvQQQwxy
  66. zQ012QQQ
  67. """
  68. print(f(to_grid(s1)))
  69. print(f(to_grid(s2)))
  70. print(f(to_grid(s3)))
  71. print(f(to_grid(s4)))
  72. print(f(to_grid(s5)))
  73. print(f(to_grid(s6)))
  74. print(f(to_grid(s7)))
  75. print(f(to_grid(s8)))
Success #stdin #stdout 0.62s 14052KB
stdin
Standard input is empty
stdout
2
12
3
3
3
3
3
3