fork download
  1. E=enumerate
  2. def S(b,x,y):
  3. for X,Y in[(x,y+1),(x,y-1),(x+1,y),(x-1,y)]:
  4. try:
  5. if X>-1<Y:yield(X,Y,b[X][Y])
  6. except:1
  7. def f(b):
  8. a,s=[],[]
  9. while o:=[(x,y,c)for x,t in E(b)for y,c in E(t)if(c in'XO')>((x,y,c)in s)]:
  10. q,A=[o[0]],[]
  11. while q:x,y,c=q.pop(0);A+=(x,y,c),;q+=[i for i in S(b,x,y)if(c==i[-1])>(i in A)]
  12. a+=A,;s+=A
  13. for i in a:
  14. for x,y,_ in i:b[x][y]=str(len({k for X,Y,_ in i for k in S(b,X,Y)if'.'==k[-1]}))
  15. return'\n'.join(map(' '.join,b)).replace('.','0')
  16.  
  17. def to_board(s):
  18. return [[b for b in i if b != ' ']for i in filter(None, s.split('\n'))]
  19.  
  20. b1 = to_board(""". . O .
  21. . X X .
  22. . X . .
  23. . O O .""")
  24. b2 = to_board(""". X X .
  25. X . X O
  26. X X O .""")
  27. b3 = to_board(""". X . O""")
  28. b4 = to_board("""X
  29. X
  30. .
  31. .
  32. O
  33. .""")
  34. print(f(b1))
  35. print('-'*20)
  36. print(f(b3))
  37. print('-'*20)
  38. print(f(b4))
  39. print('-'*20)
  40. print(f(b2))
Success #stdin #stdout 0.09s 14152KB
stdin
Standard input is empty
stdout
0 0 2 0
0 5 5 0
0 5 0 0
0 3 3 0
--------------------
0 2 0 1
--------------------
1
1
0
0
2
0
--------------------
0 3 3 0
2 0 3 2
2 2 1 0