|
| 1 | +import collections |
| 2 | + |
| 3 | + |
| 4 | +def get_acceptable_steps(i, j): |
| 5 | + template = {(i + 1, j - 2), (i + 1, j + 2), (i - 1, j - 2), |
| 6 | + (i - 1, j + 2), (i + 2, j - 1), (i + 2, j + 1), |
| 7 | + (i - 2, j + 1), (i - 2, j - 1)} |
| 8 | + return {x for x in template if 0 <= x[0] <= 7 and 0 <= x[1] <= 7} |
| 9 | + |
| 10 | + |
| 11 | +def generate_horse_graph(): |
| 12 | + graph = collections.defaultdict(set) |
| 13 | + for i in range(8): |
| 14 | + for j in range(8): |
| 15 | + graph[(i, j)] = graph[(i, j)] | get_acceptable_steps(i, j) |
| 16 | + |
| 17 | + return dict(graph) |
| 18 | + |
| 19 | + |
| 20 | +def path(graph, start, goal): |
| 21 | + paths = collections.deque([[start]]) |
| 22 | + extended = set() |
| 23 | + while len(paths) != 0: |
| 24 | + current_path = paths.popleft() |
| 25 | + current_point = current_path[-1] |
| 26 | + if current_point == goal: |
| 27 | + return current_path |
| 28 | + elif current_point in extended: |
| 29 | + continue |
| 30 | + extended.add(current_point) |
| 31 | + transforms = graph[current_point] |
| 32 | + for word in transforms: |
| 33 | + if word not in current_path: |
| 34 | + paths.append(current_path[:] + [word]) |
| 35 | + return [] |
| 36 | + |
| 37 | + |
| 38 | +def bfs_paths(graph, start, goal): |
| 39 | + queue = [(start, [start])] |
| 40 | + while queue: |
| 41 | + (vertex, path) = queue.pop(0) |
| 42 | + for next in graph[vertex] - set(path): |
| 43 | + if next == goal: |
| 44 | + yield path + [next] |
| 45 | + else: |
| 46 | + queue.append((next, path + [next])) |
| 47 | + |
| 48 | + |
| 49 | +graph = generate_horse_graph() |
| 50 | +# print graph |
| 51 | +sp = (0, 0) |
| 52 | +ep = (4, 3) |
| 53 | + |
| 54 | +# print path(graph, sp, ep) |
| 55 | +gen = bfs_paths(graph, sp, ep) |
| 56 | +print gen.next() |
0 commit comments