fork download
  1. E=enumerate
  2. M={(1,0):'|',(-1,0):'|',(0,-1):'-',(0,1):'-'}
  3. def f(m):
  4. d={(x,y):v for x,r in E(m)for y,v in E(r)};q=[i for i in d if'#'==d[i]];C=0
  5. while q:
  6. Q,S=[q[0]],[[],[q[0]]];q={*q}-{q[0]};C+=1
  7. for x,y in Q:
  8. for X,Y in M:
  9. if(V:=(x+X,y+Y))in q or(d.get(V)in M.values())>(V in S[0]):S[V in q]+=V,;Q+=V,;q=[*{*q}-{V}]
  10. for x,y in S[0]:
  11. for X,Y in M:S[0]+=[V:=(x+X,y+Y)]*((M[(X,Y)]==d[(x,y)])>(V in S[0])<(d.get(V)==d[(x,y)]))
  12. return C
  13.  
  14. s1 = """
  15. ##|
  16. #### |
  17. # ##
  18. # # |##
  19. ---- |######
  20. | ###
  21. |## |## #
  22. |## - |######
  23. # |####
  24. """
  25. s2= """
  26. # ##
  27. - ##
  28. ##
  29. ####
  30. # #
  31. ----
  32. """
  33. s3 = """
  34. #
  35. |### #
  36. | # #
  37. |#### -
  38. """
  39. s4= """
  40. --- ##|
  41. ### ##|
  42. ###
  43. ### |#
  44. """
  45. s5= """
  46. #### #####|
  47. # ##
  48. ### |# |#
  49. ##### |# |##
  50. ----- |# |#
  51. |#
  52. |#
  53. |#
  54. """
  55. s6 = """
  56. |# |# |# |# |# #| #| #|
  57. """
  58. s7= """
  59. |##
  60. | ##
  61. |# --
  62. """
  63. s8= """
  64. |##
  65. ---- |####
  66. # ##
  67. ### |#
  68. |# ###|
  69. |# #|
  70. |# ##|
  71. |#
  72. """
  73. s9 = """
  74. - |##
  75. # #
  76. #| ###
  77. #| ---
  78. """
  79. s10 = """
  80. #
  81. ####
  82. ----
  83.  
  84. --
  85. #
  86. """
  87. s11 = """
  88. ##
  89. ##
  90. --
  91.  
  92. --
  93. ##
  94. ##
  95. """
  96. def to_board(s):
  97. return [[*i] for i in filter(None, s.split('\n'))]
  98.  
  99. print(f(to_board(s1)))
  100. print(f(to_board(s2)))
  101. print(f(to_board(s3)))
  102. print(f(to_board(s4)))
  103. print(f(to_board(s5)))
  104. print(f(to_board(s6)))
  105. print(f(to_board(s7)))
  106. print(f(to_board(s8)))
  107. print(f(to_board(s9)))
  108. print(f(to_board(s10)))
  109. print(f(to_board(s11)))
Success #stdin #stdout 0.08s 14124KB
stdin
Standard input is empty
stdout
5
2
2
3
4
8
2
4
4
2
2