fork download
  1. E=enumerate
  2. def F(s,c,C,O,e,M,x,y,U):
  3. r=[]
  4. for X,Y in s:e[(x,y)]=e.get((x,y),[])+[((X,Y),c)];r+=(O+[(x,y)],X,Y,c-C*~-((X,Y)in U),M,U+[(X,Y)]*C),
  5. return r
  6. def f(b):
  7. d,D={4:[]},[]
  8. for x,r in E(b):
  9. for y,v in E(r):d[K]=d.get(K:=4-(v=='$')-2*(v=='#')-3*(v=='.')-4*('@'==v),[])+[(x,y)];D+=(x,y),
  10. C,e=[],{};q=[([],*d[0][0],0,set(),[])]
  11. while q:
  12. O,x,y,c,M,U=q.pop(0)
  13. if c==len(d[3]):return c
  14. o={a:[(x+X,y+Y)for X in[-1,0,1]for Y in[-1,0,1]if X or Y if(P:=(x+X,y+Y))in b if[]==[1for(J,K),w in e.get((x,y),[])if(J,K)==P and w>=c]]for a,b in d.items()}
  15. if not M&{*o[4]}:C+=c,;q=F(o[3],c,1,*(P:=[O,e,{*o[4]},x,y,U]))+q+F(o[1],c,0,*P)+F(o[0],c,0,*P)
  16. return max(C+[0])
  17.  
  18. s1 = """
  19. @..
  20. .$.
  21. ...
  22. """
  23. s2 = """
  24. @....
  25. ...g$
  26. .....
  27. """
  28. s3 = """
  29. @....
  30. ...$g
  31. .....
  32. """
  33. s4 = """
  34. @....g..
  35. .......$
  36. ........
  37. .....h..
  38. """
  39. s5 = """
  40. @....z..
  41. .......$
  42. .....b..
  43. """
  44. s6 = """
  45. @$#.
  46. ###$
  47. ....
  48. """
  49. s7 = """
  50. @..#..
  51. $.$g.$
  52. ...#..
  53. """
  54. s8 = """
  55. @#.d#$
  56. $...##
  57. e.....
  58. ..$...
  59. ##..$b
  60. .#..g$
  61. """
  62. s9 = """
  63. ..12345678
  64. a.@....g.D
  65. b........$
  66. c.......#.
  67. d......h..
  68. """
  69. s10 = """
  70. ..12345678
  71. a.@....g.D
  72. b........$
  73. c........#
  74. d......h..
  75. """
  76. s11 = """
  77. ..12345678
  78. a.@....g.D
  79. b.......#$
  80. c........#
  81. d......h..
  82. """
  83. def to_board(D):
  84. return [*filter(None, D.split('\n'))]
  85. print(f(to_board(s1)))
  86. print(f(to_board(s2)))
  87. print(f(to_board(s3)))
  88. print(f(to_board(s4)))
  89. print(f(to_board(s5)))
  90. print(f(to_board(s6)))
  91. print(f(to_board(s7)))
  92. print(f(to_board(s8)))
  93. print(f(to_board(s9)))
  94. print(f(to_board(s10)))
  95. print(f(to_board(s11)))
Success #stdin #stdout 0.13s 14156KB
stdin
Standard input is empty
stdout
1
0
1
1
0
1
2
3
1
1
1