fork download
  1. A=abs
  2. M=[(0,1),(0,-1),(1,0),(-1,0)]
  3. def F(b,x,y,X,Y,s):
  4. q=[z:=(X,Y)];s+=z,
  5. while q:
  6. X,Y=q.pop(0)
  7. for J,K in M:
  8. if((U:=(X+J,Y+K))in s)<(' '==b[X+J][Y+K]):yield(*U,(J,K));q+=U,;s+=U,
  9. def f(b,c,C):
  10. (y,x),(Y,X)=c,C;q=[(X,Y,*([[(-1,0),(1,0)][x<X],[(0,-1),(0,1)][y<Y]][x==X]),[])]
  11. while q:
  12. X,Y,j,k,s=q.pop(0);w=A(z:=x-X)+A(Z:=y-Y);P=w>2;T=[((J,K),any(B!=(J,K)for B in F(b,x,y,X+J,Y+K,[(X,Y)])))for J,K in M if((X+J,Y+K)in s)<(' '==b[X+J][Y+K])and w<A(z-J)+A(Z-K)];T=[(a,b)for a,b in T if~-any(B for _,B in T)-b]
  13. if[]==T or(len(T)==1>T[0][1]or any(i[0]!=(j,k)for i in T))*P:return(X,Y)
  14. if(K:=[(0,j),(-k,0)][k>0])in[i[0]for i in T]*P:return(X+K[0],Y+K[1])
  15. for(J,K),_ in T:q+=(X+J,Y+K,J,K,s+[(X+J,Y+K)]),
  16.  
  17. def to_board(S):
  18. return[[*i]for i in filter(None, S.split('\n'))]
  19. s1 = """
  20. #############
  21. ######## # ##
  22. ####### #
  23. ########## ##
  24. ## P B #
  25. #### ########
  26. #############
  27. """
  28. s2 = """
  29. #############
  30. ######## # ##
  31. ####### #
  32. ########## ##
  33. ## P B #
  34. #### ########
  35. #############
  36. """
  37. s3 = """
  38. ############################
  39. #P B #
  40. ######################### ##
  41. ############################
  42. """
  43. s4 = """
  44. ######
  45. ### ##
  46. #P B##
  47. ### #
  48. ######
  49. """
  50. s5 = """
  51. #######
  52. ### ##
  53. ## B###
  54. ## ###
  55. ###P###
  56. #######
  57. """
  58. s6 = """
  59. #######
  60. #P B #
  61. #######
  62. """
  63. s7 = """
  64. #######
  65. # P B #
  66. #######
  67. """
  68. s8 = """
  69. #######
  70. # PB #
  71. #######
  72. """
  73. print(f(to_board(s1),(5, 4),(7, 4)))
  74. print(f(to_board(s2),(8, 4),(10, 4)))
  75. print(f(to_board(s3),(1, 1),(3, 1)))
  76. print(f(to_board(s4),(1, 2),(3, 2)))
  77. print(f(to_board(s5),(3, 4),(3, 2)))
  78. print(f(to_board(s6),(1, 1),(4, 1)))
  79. print(f(to_board(s7),(2, 1),(4, 1)))
  80. print(f(to_board(s7),(3, 1),(4, 1)))
Success #stdin #stdout 0.07s 14068KB
stdin
Standard input is empty
stdout
(4, 10)
(2, 10)
(1, 25)
(3, 3)
(2, 2)
(1, 4)
(1, 5)
(1, 5)