diff --git a/Chapitre 4 - Graphes/C08_labyrinthe.py b/Chapitre 4 - Graphes/C08_labyrinthe.py index 34c3602..957d91b 100644 --- a/Chapitre 4 - Graphes/C08_labyrinthe.py +++ b/Chapitre 4 - Graphes/C08_labyrinthe.py @@ -277,5 +277,28 @@ def genere_labirinthe_aleatoire(nb_salles, max_aretes): return l -print(genere_labirinthe_aleatoire(10, 10).montrer()) +#print(genere_labirinthe_aleatoire(10, 10).montrer()) +def inside(x, y, nb_salles): + return x >= 0 and x < nb_salles and y >= 0 and y < nb_salles + +def vrai_labyrinthe(nb_salles): + if nb_salles % 2 == 0: nb_salles += 1 + nodes = [[x % 2 == 0 or y % 2 == 0 for x in range(nb_salles)] for y in range(nb_salles)] + visited = set([(1, 1)]) + stack = [(1, 1)] + while stack: + x, y = stack[-1] + directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] + directions = [(dx, dy) for dx, dy in directions if inside(x+dx*2, y+dy*2, nb_salles)] + directions = [(dx, dy) for dx, dy in directions if (x+dx*2, y+dy*2) not in visited] + if not directions: + stack.pop() + else: + dx, dy = choice(directions) + nodes[x+dx][y+dy] = False + stack.append((x+dx*2, y+dy*2)) + visited.add((x+dx*2, y+dy*2)) + return Labyrinthe([[Salle(node) for node in row] for row in nodes], (1, 1), (nb_salles-2, nb_salles-2)) + +print(vrai_labyrinthe(40).montrer())