Skip to content

Instantly share code, notes, and snippets.

@RecursiveG
Created October 31, 2013 13:18
Show Gist options
  • Save RecursiveG/7249542 to your computer and use it in GitHub Desktop.
Save RecursiveG/7249542 to your computer and use it in GitHub Desktop.
Maze Generator using DFS
import random
n=int(input("N:"))
m=int(input("M:"))
k1=int(input("K1:"))
k2=int(input("K2:"))
r=int(input("R:"))
g=[]
t=[]
def ok(x,y):
t=0
if g[x][y+1]:t+=1
if g[x][y-1]:t+=1
if g[x+1][y]:t+=1
if g[x-1][y]:t+=1
return(t==3)
for i in range(0,n+2):
t.append(True)
for i in range(0,m+2):
g.append(t.copy());
for i in range(0,n+2):
g[0][i]=False
g[m+1][i]=False
for i in range(0,m+2):
g[i][0]=False
g[i][n+1]=False
for i in range(k1,k1+r):
for j in range(k2,k2+r):
g[i][j]=False
g[2][2]=False
l=[(2,2),]
while len(l)!=0:
t=[]
p=l[-1]
x=p[0]
y=p[1]
#print("x",x,"y",y)
g[x][y]=False
if g[x+1][y]and ok(x+1,y):
t.append((x+1,y))
if g[x-1][y]and ok(x-1,y):
t.append((x-1,y))
if g[x][y+1]and ok(x,y+1):
t.append((x,y+1))
if g[x][y-1]and ok(x,y-1):
t.append((x,y-1))
if len(t)>0:
l.append(random.choice(t))
else:
l.pop()
for i in range(1,m+1):
for j in range(1,n+1):
if g[i][j]:
print("#",end="")
else:
print(".",end="")
print("")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment