view graphs_trees/find_flag/solution.py @ 0:20fea762903e

Import some exercises and solutions
author Louis Opter <kalessin@kalessin.fr>
date Sat, 29 Jun 2013 19:30:31 -0700
parents
children
line wrap: on
line source

#!/usr/bin/env python

# given:

def maze_has_flag(x, y): # x, y coordinates → bool
    return x == 3 and y == 5

def maze_has_move(x1, y1, x2, y2): # can you move from point a to b → bool
    return True

# write this to find the flag in the maze and display the coordinates walked on
# def maze_find_flag(size_x, size_y, start_x, start_y):

class Node:
    def __init__(self, x, y, visited):
        self.x = x
        self.y = y
        self.visited = visited

class Maze:
    def __init__(self, size_x, size_y):
        self._size_x = size_x
        self._maze = [False] * (size_x * size_y)

    def _get(self, x, y):
        return self._maze[y * self._size_x + x]

    def visit(self, x, y):
        print("visiting {0}, {1}".format(x, y))
        self._maze[y * self._size_x + x] = True

    def up(self, node):
        x = node.x
        y = node.y + 1
        return Node(x, y, self._get(x, y))

    def down(self, node):
        x = node.x
        y = node.y - 1
        return Node(x, y, self._get(x, y))

    def left(self, node):
        x = node.x - 1
        y = node.y
        return Node(x, y, self._get(x, y))

    def right(self, node):
        x = node.x + 1
        y = node.y
        return Node(x, y, self._get(x, y))

def maze_find_flag(size_x, size_y, start_x, start_y):
    maze = Maze(size_x, size_y)
    queue = [Node(start_x, start_y, False)]

    while queue:
        cur = queue.pop()
        maze.visit(cur.x, cur.y)
        if maze_has_flag(cur.x, cur.y):
            return True
        adjacents = [
            maze.up(cur), maze.down(cur), maze.left(cur), maze.right(cur)
        ]
        for node in filter(lambda n: not n.visited, adjacents):
            if maze_has_move(cur.x, cur.y, node.x, node.y):
                queue.insert(0, node)

maze_find_flag(10, 10, 4, 4)