Skip to content

Instantly share code, notes, and snippets.

@samhann
Created February 22, 2023 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samhann/a76abaa55e816565ead6281c56d23f6f to your computer and use it in GitHub Desktop.
Save samhann/a76abaa55e816565ead6281c56d23f6f to your computer and use it in GitHub Desktop.
Maze generator to Python New Bing
# Import random module for shuffling and sampling
import random
# Define a function that returns a spanning tree from a graph using loop-erased random walk
def spanning_tree(vertices, adjacency_list):
# Initialize an empty list for the spanning tree
spanning_tree = []
# Initialize a list of visited vertices with 0 values
visited = [0] * vertices
# Create a list of nodes from 0 to vertices - 1
nodes = list(range(vertices))
# Shuffle the nodes randomly
random.shuffle(nodes)
# Mark the first node as visited with value 1
visited[nodes[0]] = 1
# Loop through the remaining nodes
for i in range(1, vertices):
# If the node is already visited, skip it
if visited[nodes[i]]:
continue
# Otherwise, perform loop-erased random walk from the node and update the spanning tree and visited list
spanning_tree, visited = lerw(nodes[i], i + 1, adjacency_list, spanning_tree, visited)
# Return the spanning tree as output
return spanning_tree
# Define a helper function that performs loop-erased random walk from a given vertex and returns an updated spanning tree and visited list
def lerw(vertex, round, adjacency_list, spanning_tree, visited):
# Initialize an empty list for storing current path
current = []
# Loop until vertex is not visited
while not visited[vertex]:
# Mark vertex as visited with round value
visited[vertex] = round
# Append vertex to current path
current.append(vertex)
# Choose next vertex randomly from adjacency list excluding negative values
next_vertex = random.choice([v for v,_ in adjacency_list[vertex] if v >=0])
if visited[next_vertex] == round:
# Erase loop by popping vertices from current path until next_vertex is reached and marking them as unvisited
while vertex != next_vertex:
vertex = current.pop()
visited[vertex] = False
# Update vertex with next_vertex
vertex = next_vertex
# Append final vertex to current path
current.append(vertex)
# Extend spanning tree with pairs of adjacent vertices in current path
for i in range(len(current) -1):
spanning_tree.append((current[i],current[i+1]))
return (spanning_tree ,visited)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment