fork download
  1. E=enumerate
  2. def f(s):
  3. d={(x,y):v for x,r in E(s)for y,v in E(r)};q={(x,y):T[d[(x,y)]]for x,y in d if(' '==d[(x,y)])in(T:={d.get(V:=(x+X,y+Y),0):V for X,Y in[(1,0),(0,1),(-1,0),(0,-1)]})and d[(x,y)]in T};r={}
  4. while q:
  5. x,y=V=[*q][0];J,K=q.pop(V);X,Y=J-x,K-y;l=[]
  6. while d.get(W:=(x+X,y+Y),' ').isalpha():l+=d[W],;x,y=W;q.pop(W,0)
  7. r[d[V]]={*l}-{d[V]}
  8. q=[(T:=''.join(i for i in r if not r[i]),T)]
  9. for a,b in q:
  10. if''==(Q:=''.join(k for k in r if any(u in r[k]for u in a))):return b[::-1]
  11. q+=(Q,b+Q),
  12.  
  13. s1 = """
  14. R
  15. R
  16. BBRBB
  17. R
  18. """
  19. s2 = """
  20. GY
  21. GY
  22. RRRRGYRRR
  23. GY
  24. GY
  25. BBBBBBBB
  26. GY
  27. GY
  28. """
  29. s3 = """
  30. R P
  31. R P
  32. AAAARAAAAPA
  33. R P
  34. R P
  35. GGGGRGGG P
  36. R
  37. """
  38. s4 = """
  39. O Y
  40. RRRYR
  41. O Y
  42. GOGGG
  43. O Y
  44. """
  45. s5 = """
  46. YYYB
  47. B
  48. B
  49. """
  50. def to_board(s):
  51. return [[*i] for i in filter(None, s.split('\n'))]
  52.  
  53. print(f(to_board(s1)))
  54. print(f(to_board(s2)))
  55. print(f(to_board(s3)))
  56. print(f(to_board(s4)))
  57. print(f(to_board(s5)))
Success #stdin #stdout 0.1s 14100KB
stdin
Standard input is empty
stdout
BR
RYGB
GAPR

YB