fork(2) download
  1. from sys import stdout
  2. from collections import deque
  3. from types import MappingProxyType
  4. import io
  5. import os
  6.  
  7. input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
  8.  
  9. SIZE, EMPTY, VISITED, START, COLLISION, OFFSETS = 201, ".", "@", "#", "X", MappingProxyType(
  10. dict(N=(0, 1), E=(1, 0), S=(0, -1), W=(-1, 0))
  11. )
  12.  
  13. n = int(input())
  14.  
  15. while n:
  16. n -= 1
  17. path = input().decode().strip()
  18. curr = [SIZE // 2, SIZE // 2]
  19.  
  20. matrix = [[EMPTY] * SIZE for i in range(SIZE)]
  21. if path:
  22. matrix[curr[1]][curr[0]] = START
  23.  
  24. stack = deque()
  25.  
  26. # Cleaning the path from backtracking:
  27. for step in path:
  28. if any((
  29. stack and step == "N" and stack[-1] == "S",
  30. stack and step == "S" and stack[-1] == "N",
  31. stack and step == "E" and stack[-1] == "W",
  32. stack and step == "W" and stack[-1] == "E",
  33. )):
  34. stack.pop()
  35. continue
  36.  
  37. stack.append(step)
  38.  
  39. found = False
  40.  
  41. # Processing the path:
  42. for step in stack:
  43. ox, oy = OFFSETS[step]
  44. x, y = curr
  45. newx, newy = x + ox, y + oy
  46. curr = [newx, newy]
  47. if matrix[newy][newx] != EMPTY:
  48. matrix[newy][newx] = COLLISION
  49. found = True
  50. break
  51. matrix[newy][newx] = VISITED
  52.  
  53. stdout.write("TAK\n" if found else "NIE\n")
Success #stdin #stdout 0.04s 10392KB
stdin
8

WSWSWS
WEWEWE
WSEN
SEEES
EEEENWWSS
NNEESSNNWWSS
ENNSWS
stdout
NIE
NIE
NIE
TAK
NIE
TAK
NIE
TAK