Last active
August 29, 2015 14:22
-
-
Save adusak/b43906eb5f8e198e0377 to your computer and use it in GitHub Desktop.
Solver of number maze
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from operator import itemgetter | |
| import numpy as np | |
| def load_labyrinth(name): | |
| file = open("labs/" + name, 'r') | |
| text = file.read() | |
| lines = text.split("\n") | |
| rows = [] | |
| for line in lines: | |
| column = [] | |
| for col in line.split(" "): | |
| column.append(col) | |
| rows.append(column) | |
| table = np.array(rows) | |
| gr = {} | |
| coor_str = lambda x, y: str(x) + "," + str(y) | |
| print(table) | |
| for i in range(len(table)): | |
| for j in range(len(table[i])): | |
| val = int(table[i, j]) | |
| name = coor_str(i, j) | |
| gr[name] = set() | |
| if i - val >= 0: | |
| gr[name].add(coor_str(i - val, j)) | |
| if i + val < len(table): | |
| gr[name].add(coor_str(i + val, j)) | |
| if j - val >= 0: | |
| gr[name].add(coor_str(i, j - val)) | |
| if j + val < len(table[i]): | |
| gr[name].add(coor_str(i, j + val)) | |
| return gr, coor_str(0, 0), coor_str(len(table) - 1, len(table[0]) - 1) | |
| def solve(graph, start, end, path=[]): | |
| path = path + [start] | |
| if start == end: | |
| return [path] | |
| if start not in graph.keys(): | |
| return [] | |
| paths = [] | |
| for node in graph[start] - set(path): | |
| new_paths = solve(graph, node, end, path) | |
| for new_path in new_paths: | |
| paths.append(new_path) | |
| return paths | |
| def solve_minimal(graph, start, end): | |
| return min(map(lambda x: (len(x), x), solve(graph, start, end)), key=itemgetter(0))[1] | |
| graph, start, end = load_labyrinth("num_lab_2.txt") | |
| print(solve(graph, start, end)) | |
| print(solve_minimal(graph, start, end)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment