Skip to content

Instantly share code, notes, and snippets.

@samagragupta
Created January 20, 2020 16:48
Show Gist options
  • Select an option

  • Save samagragupta/b9a7c639f2522baf3461492ac743fe48 to your computer and use it in GitHub Desktop.

Select an option

Save samagragupta/b9a7c639f2522baf3461492ac743fe48 to your computer and use it in GitHub Desktop.
class Node:
parent = None
def __init__(self,state):
self.state = state
def setParent(self,parent):
self.parent = parent
def Backtrack(p):
count=0
while p.parent!=None:
print(p.state)
p = p.parent
count+=1
print(p.state)
print(count)
def checkInClose(z,close):
for i in close:
if i.state==z:
return False
return True
def checkAndCreateNodeLeft(z,open1,close,p):
if (z[0]<=z[1] or (z[1]==0 and z[0]>=0)) and (z[3]<=z[4] or (z[4]==0 and z[3]>=0)):
z[2] = 'R'
if checkInClose(z,close):
x = Node(z)
x.setParent(p)
open1.append(x)
def checkAndCreateNodeRight(z,open1,close,p):
if (z[0]<=z[1] or (z[1]==0 and z[0]>=0)) and (z[3]<=z[4] or (z[4]==0 and z[3]>=0)):
z[2] = 'L'
if checkInClose(z,close):
x = Node(z)
x.setParent(p)
open1.append(x)
def MoveGen(p,open1,close):
li = p.state.copy()
z = li.copy()
# boat is at left side
if z[2]=='L':
#moving 2 cannib
if z[0]>1:
z[0] = z[0]-2
z[3] = z[3]+2
checkAndCreateNodeLeft(z,open1,close,p)
# moving 2 missionaries
z = li.copy()
if z[1]>1:
z[1] = z[1]-2
z[4] = z[4]+2
checkAndCreateNodeLeft(z,open1,close,p)
# moving 1 missionary and 1 cannibal
z = li.copy()
if z[0]>0 and z[1]>0:
z[0]-=1
z[1]-=1
z[3]+=1
z[4]+=1
checkAndCreateNodeLeft(z,open1,close,p)
# for boat is at right side
z = li.copy()
if z[2] == 'R':
# moving 1 cannibal
if z[3]>0:
z[3]-=1
z[0]+=1
checkAndCreateNodeRight(z,open1,close,p)
# moving 1 missionary
z = li.copy()
if z[4]>0:
z[4]-=1
z[1]+=1
checkAndCreateNodeRight(z,open1,close,p)
# move 1 miss and 1 cann
z = li.copy()
if z[3]>0 and z[4]>0:
z[3]-=1
z[4]-=1
z[0]+=1
z[1]+=1
checkAndCreateNodeRight(z,open1,close,p)
# moving 2 cann
z = li.copy()
if z[3]>1:
z[0]+=2
z[3]-=2
checkAndCreateNodeRight(z,open1,close,p)
# moving 2 miss
z = li.copy()
if z[4]>1:
z[1]+=2
z[4]-=2
checkAndCreateNodeRight(z,open1,close,p)
init_state = [3,3,'L',0,0]
goal_state = [0,0,'R',3,3]
root = Node(init_state)
open1 = [root]
close = []
while(len(open1)>0):
p = open1[-1]
close.append(open1[-1])
open1.pop(-1)
if (p.state==goal_state):
Backtrack(p)
break
else:
MoveGen(p,open1,close)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment