示例#1
0
def BFS(start, goal):
    
    notVis = []
    pathLen = 0
    nodeCount = 0
    goalHash = Common.stateToHash(goal)
    #children = []
    n = stateToNode(start, None)
    
    if(Common.stateToHash(n.curState) == goalHash):
        return [True, 0]
    
    vis = []
    vis.append(Common.stateToHash(n.curState))
    
    while True:   
        children = []
        if(notVis.__len__() != 0):
            n = notVis.pop(0)
        
        succ = generateSuccesorStates(n.curState)
        
        if succ.__len__() == 0:
            break
        for x in succ:
            child = stateToNode(x, n)
            children.append(child)
            
        for i in children:
            curHash = Common.stateToHash(i.curState)
            nodeCount = nodeCount+1
            
            if(curHash not in vis):
                if(curHash == goalHash):
                    #path = getPath(i, (pathLen+1))
                    path = getPath(i)
                    for j in reversed(path):
                        displayBoard(j)
                        print""
                    print "Number of Nodes Expanded: ", nodeCount
                    stateStrings = Common.pathString(path)
                    return stateStrings
               
                notVis.append(i)
                vis.append(curHash)
        pathLen = pathLen + 1
        
    print "No path Found"
    return []
示例#2
0
def DFS(start, goal):
    #convert goal state to hash string
    g = Common.stateToHash(goal)
    #make the list of visted an empty list
    vis = []
    d = 'n'
    res = dfs_rec(start, d, vis, g)
    if(res): 
        print("found goal state")
        print(path)
    else:
        print("did not find goal state")
示例#3
0
def dfs_rec(oldCur, d, oldVis, goal):
    cur = copy.deepcopy(oldCur)
    vis = copy.deepcopy(oldVis)
    #change current state in the direction of d 
    cur = Common.mod(cur, d)  
    
    #if our current state could not be reached (ie trying to swap with outside of the matrix) don't check this branch
    if(cur == None):
        return False
    hashstate = Common.stateToHash(cur)
    #if we are the goal state return our current state and true
    if(hashstate == goal):
        path.insert(0, cur)
        return True
    #if this is a visited state stop
    if(hashstate in vis):
        return False
    #if not visited then add it to the visited list
    else:
        vis.append(hashstate)
    #check right move
    ret = dfs_rec(cur, 'l', vis, goal)
    if(ret == True):
        path.insert(0, cur)
        return True
    #check left move
    ret = dfs_rec(cur, 'r', vis, goal)
    if(ret == True):
        path.insert(0, cur)
        return True
    #check up move
    ret = dfs_rec(cur, 'u', vis, goal)
    if(ret == True):
        path.insert(0, cur)
        return True
    #check left move
    ret = dfs_rec(cur, 'd', vis, goal)
    if(ret == True):
        path.insert(0, cur)
        return True
    else:
        return False