b.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import os, argparse
  2. def solve_task(lines):
  3. start = None
  4. tiles = [[Vertex() for j in range(len(lines[0]))] for i in range(len(lines))]
  5. for y, line in enumerate(lines):
  6. for x, char in enumerate(line):
  7. value = char
  8. if value == 'S':
  9. value = 'a'
  10. elif value == 'E':
  11. value = 'z'
  12. start = tiles[y][x]
  13. tiles[y][x].value = ord(value)
  14. for y, row in enumerate(tiles):
  15. for x, vert in enumerate(row):
  16. if x > 0:
  17. conditional_add_neighbour(vert, tiles[y][x-1])
  18. if x < (len(row)-1):
  19. conditional_add_neighbour(vert, tiles[y][x+1])
  20. if y > 0:
  21. conditional_add_neighbour(vert, tiles[y-1][x])
  22. if y < (len(tiles)-1):
  23. conditional_add_neighbour(vert, tiles[y+1][x])
  24. distance = BFS(start, ord('a'))
  25. print(f"The shortest path is {distance}")
  26. def BFS(start, goal_value):
  27. nodes_to_search = [start]
  28. start.distance = 0
  29. while len(nodes_to_search) > 0:
  30. current_node = nodes_to_search.pop(0)
  31. if current_node.visited:
  32. continue
  33. current_node.visited = True
  34. if current_node.value == goal_value:
  35. return current_node.distance
  36. for n in current_node.neighbours:
  37. if not n.visited:
  38. n.distance = current_node.distance + 1
  39. nodes_to_search.append(n)
  40. return "No path"
  41. def conditional_add_neighbour(src, dest):
  42. if src.value-dest.value <= 1:
  43. src.add_neighbour(dest)
  44. class Vertex:
  45. def __init__(self, value = None) -> None:
  46. self.neighbours = []
  47. self.value = value
  48. self.visited = False
  49. def add_neighbour(self, other_vertex):
  50. #n = Edge(self, other_vertex)
  51. self.neighbours.append(other_vertex)
  52. class Edge:
  53. def __init__(self, src, dest) -> None:
  54. self.src = src
  55. self.dest = dest
  56. pass
  57. def read_lines(filename):
  58. lines = []
  59. with open(filename) as infile:
  60. for raw_line in infile:
  61. line = raw_line.rstrip()
  62. lines.append(line)
  63. return lines
  64. def parse_arguments():
  65. parser = argparse.ArgumentParser(description="Script that solves the case",epilog="Have a nice day!")
  66. parser.add_argument('filename', nargs='?', default="example.txt", help='Input file')
  67. args = parser.parse_args()
  68. return args
  69. def main():
  70. args = parse_arguments()
  71. lines = read_lines(args.filename)
  72. solve_task(lines)
  73. if __name__ == "__main__":
  74. main()