Ejemplo n.º 1
0
def main():
    """ Initial state node """
    initialState = nodo.node(None, ist0)
    #initialState.randMatrix()
    """ Final state node """
    finalState = nodo.node(None, fst0)

    print('\n\nInitial state:')
    initialState.printM()
    print('Final state')
    finalState.printM()
    """ Try to solve the puzzle using best first search """
    bfs_solution = bfs.astar(initialState, finalState)
    """ Try to solve the puzzle using A* """
    #path1 = bfs.astar(initialState,finalState)
    """ Print the path to file """
    if len(bfs_solution[0]) > 0:
        with open('bfs_solution.txt', 'w') as file:
            file.write('Solution statistics:')
            file.write('\n\nNode expansions: ' + str(bfs_solution[1]))
            file.write('\nBlock movements: ' + str(bfs_solution[2]))
            file.write('\nSolution time: ' + str(bfs_solution[3]))
            file.write('\n\n\n')
            for matrix in bfs_solution[0]:
                for row in matrix:
                    file.write(str(row))
                    file.write('\n')
                    file.write('\n')
Ejemplo n.º 2
0
 def __init__(self, matrix):
     n = 0
     for x in range(len(matrix)):
         nodos = []
         for y in range(len(matrix)):
             if int(matrix[x][y][0]) == 255 and int(
                     matrix[x][y][1]) == 0 and int(
                         matrix[x][y][2]) == 0 and n == 0:
                 nodos.append(
                     node(True, x, y,
                          (int(matrix[x][y][0]), int(
                              matrix[x][y][1]), int(matrix[x][y][2]))))
                 n = 1
             else:
                 nodos.append(
                     node(False, x, y,
                          (int(matrix[x][y][0]), int(
                              matrix[x][y][1]), int(matrix[x][y][2]))))
         self.nodes.append(nodos)
Ejemplo n.º 3
0
def bfsearch(start, goal):
    openl = []  # Open nodes list
    closedl = []  # Closed nodes list
    path = []  # Path of the solution
    moves = 0  # Number of movements to solve the puzzle
    expansions = 0  # Number of node expansions
    start_time = time.time()  # Start time of the search

    start.h = 0
    openl.append([start.h, start])

    while openl:
        current = openl.pop(0)  # Pop item from queue
        cm = current[1].matrix
        gm = goal.matrix
        if cm == gm:
            end_time = time.time()  # End time of the search
            # Form the path by going from
            # the goal node to the root node
            node = current[1]
            while node.parent:
                path.append(node.matrix)
                node = node.parent
                moves += 1
            path.append(node.matrix)
            break
        else:
            # Expanssion of the valid nodes (returns a matrix)
            for node_matrix in validMoves(current[1]):
                if node_matrix not in closedl:
                    n = nodo.node(current[1], node_matrix)
                    n.h = n.heuristic(goal.matrix)
                    current[1].childs.append([n.h, n])
                    openl.append([n.h, n])

            openl = sorted(openl,
                           key=lambda x: x[0])  # Sort list based on heuristic
            closedl.append(current[1].matrix)
            expansions += 1

    if len(path) > 0:
        print('The puzzle was solved!')
        print('\nSolution statistics: ')
        print('\nNode expansions: ', expansions)
        print('Block movements : ', moves)
        print('Solution time: ', float(end_time - start_time), '[s]\n')
        path.reverse()
    else:
        print('\nNo solution was found...')

    return [path, expansions, moves, float(end_time - start_time)]
Ejemplo n.º 4
0
def astar(start, goal):

    openl = []
    closedl = []
    path = []
    start_time = time.time()
    expansions = 0
    moves = 0

    start.h = 0

    openl.append([start.h, start])

    while openl:

        current = openl.pop(0)
        cm = current[1].matrix
        gm = goal.matrix

        if cm == gm:
            end_time = time.time()
            node = current[1]
            while node.parent:
                path.append(node.matrix)
                node = node.parent
                moves += 1
            path.append(node.matrix)
            break

        else:
            # Expanssion of the valid nodes (returns a matrix)
            for node_matrix in validMoves(current[1]):
                if node_matrix not in closedl:
                    n = nodo.node(current[1], node_matrix)
                    n.h = n.heuristic(goal.matrix) + n.cost()
                    current[1].childs.append([n.h, n])
                    openl.append([n.h, n])

            openl = sorted(openl,
                           key=lambda x: x[0])  # Sort list based on heuristic
            closedl.append(current[1].matrix)
            expansions += 1

    if len(path) > 0:
        print('The puzzle was solved!')
        path.reverse()
    else:
        print('\nNo solution was found...')
    return [path, expansions, moves, float(end_time - start_time)]
Ejemplo n.º 5
0
def bfsearch(N,goal):
    opnNds = []               # Open nodes list
    cldNds = []               # Closed nodes list
    path = []                 # Path of the solution
    moves = 0                 # Number of movements to solve the puzzle
    expansions = 0            # Number of node expansions 
    start_time = time.time()  # Start time of the search
    
    N.h = 0
    opnNds.append([N.h,N])
    
    while opnNds:
        current = opnNds.pop(0)                        # Pop item from queue
        cm = current[1].matrix                          
        gm = goal.matrix
        if cm == gm:
            end_time = time.time()                     # End time of the search
            # Form the path by going from
            # the goal node to the root node
            node = current
            while node[1].parent:
                path.append(node[1].matrix)
                node = node[1].parent
                moves += 1
            path.append(node[1].matrix)
            break
        else:
            # Expanssion of the valid nodes
            nsum = current[1].shiftUp()
            nsdm = current[1].shiftDown()
            nslm = current[1].shiftLeft()
            nsrm = current[1].shiftRight()
            
            if len(nsum) > 0 and nsum not in cldNds:
                nsu = nodo.node(current,nsum)          # New node creation
                nsu.h = nsu.heuristic(goal.matrix)     # Compute the heuristic
                current[1].childs.append([nsu.h,nsu])  # Append to current node's child list
                opnNds.append([nsu.h,nsu])
                
            if len(nsdm) > 0 and nsdm not in cldNds:
                nsd = nodo.node(current,nsdm)
                nsd.h = nsd.heuristic(goal.matrix)
                current[1].childs.append([nsd.h,nsd])
                opnNds.append([nsd.h,nsd])
                
            if len(nslm) > 0 and nslm not in cldNds:
                nsl = nodo.node(current,nslm)
                nsl.h = nsl.heuristic(goal.matrix)
                current[1].childs.append([nsl.h,nsl])
                opnNds.append([nsl.h,nsl])
                
            if len(nsrm) > 0 and nsrm not in cldNds:
                nsr = nodo.node(current,nsrm)
                nsr.h = nsr.heuristic(goal.matrix)
                current[1].childs.append([nsr.h,nsr])
                opnNds.append([nsr.h,nsr])
                
            opnNds = sorted(opnNds,key=lambda x: x[0]) # Sort list based on heuristic
            cldNds.append(current[1].matrix)
            expansions += 1
            
    if len(path) > 0:
        print('The puzzle was solved!')
        print('\nSolution statistics: ')
        print('\nNode expansions: ', expansions)
        print('Block movements : ', moves)
        print('Solution time: ',float(end_time-start_time),'[s]\n')
        path.reverse()
    else:
        print('\nNo solution was found...')
    return path
Ejemplo n.º 6
0
    for r in m:
        print(r)
    print('\n')

#initialState = nodo.node(None,[[1, 2, 6, 3],[4, 9, 5, 7], [8, 13, 11, 15],[12, 14, 10, 0]])
#finalState = nodo.node(None,[[0, 1, 2, 3],[4, 5, 6, 7], [8, 9, 10, 11],[12, 13, 14, 15]])
ist = randMatrix()    
fst = [[1,2,3,4],
       [5,6,7,8],
       [9,10,11,12],
       [13,14,15,0]]
       
print('Initial state:')
printM(ist)
print('Goal state:')
printM(fst)

initialState = nodo.node(None,ist)
finalState = nodo.node(None,fst)

# Try to solve puzzle using Best First Search
path = bfs.bfsearch(initialState,finalState)

# Print path to the file
if len(path) > 0:
    with open('solution.txt','w') as file:
        for matrix in path:
            for row in matrix:
                file.write(str(row))
                file.write('\n')
            file.write('\n')