Exemple #1
0
def diametro(grafo):
	"""Calcula el maximo camino minimo del grafo.
	Devuelve el camino: lista de vertices (Obj).
	Pre: El grafo existe.
	"""
	vertices = grafo.lista_de_vertices()
	maximo = 0

	for i in xrange(len(vertices)):
		bfs = BFS(grafo, vertices[i])
		for j in xrange(i+1, len(vertices)):
			distancia = bfs.distancia_a(vertices[j])
			if distancia > maximo:
				maximo = distancia
				camino = bfs.camino_minimo(vertices[j])

	return camino
Exemple #2
0
def distancias(grafo, id_vertice):
	"""Calcula todos los vertices que estan a diferentes niveles/
	distancias del vertice recibido por parametro.
	Devuelve una lista de listas de vertices(Obj). La 1er lista
	seria la del nivel 1, la segunda del nivel 2, etc..
	Pre: El grafo y el id del vertice existen.
	"""
	vertice = grafo.obtener_vertice(id_vertice)
	bfs = BFS(grafo, vertice)
	vertices_por_nivel = []

	i = 1
	while bfs.cantidad_a_nivel(i): #distinto de 0
		vertices_por_nivel.append(bfs.vertices_a_nivel(i))
		i += 1 

	return vertices_por_nivel
Exemple #3
0
def diametro(grafo):
    """Calcula el maximo camino minimo del grafo.
	Devuelve el camino: lista de vertices (Obj).
	Pre: El grafo existe.
	"""
    vertices = grafo.lista_de_vertices()
    maximo = 0

    for i in xrange(len(vertices)):
        bfs = BFS(grafo, vertices[i])
        for j in xrange(i + 1, len(vertices)):
            distancia = bfs.distancia_a(vertices[j])
            if distancia > maximo:
                maximo = distancia
                camino = bfs.camino_minimo(vertices[j])

    return camino
Exemple #4
0
def BFSAlgo(state):
    bfs = BFS()
    bfs.init()
    start = timeit.default_timer()
    bfsAlgo = bfs.doBFS(state, "1,2,5,3,4,0,6,7,8")
    path = bfsAlgo[0][0]
    depth = bfsAlgo[0][1]
    explored = bfsAlgo[1]
    stop = timeit.default_timer()
    print('============= Time =============')
    print(stop - start)
    print('============= Depth =============')
    print(depth)
    print('============= Explored =============')
    print(explored)
    print('============= Path =============')
    for i in path:
        printBoard(i.split(','))
Exemple #5
0
def run_algorithm(algorithm, board, board_size):

    logic = GameLogic(State(board), board_size)
    if algorithm == 1:
        ids = IDS(State(board), logic)
        chosen = ids.run_search()
    elif algorithm == 2:
        bfs = BFS(State(board), logic)
        chosen = bfs.run_search()
    elif algorithm == 3:
        a_star = Astar(State(board), logic)
        chosen = a_star.run_search()
    else:
        raise Exception("No algorithm was chosen")
    if chosen is not None:
        to_print = ' '.join(map(str, chosen))
        with open('output.txt', 'w') as output_file:
            output_file.write(to_print)
Exemple #6
0
def camino(grafo, id_vertice_inicial, id_vertice_final):
    """Calcula el camino minimo desde el vertice inicial
	al vertice final. Devuelve la lista de los vertices (Obj)
	que los unen (incl. inicial y final).
	Pre: el grafo y los ids de los vertices existen. Los vertices
	pertenecen al grafo en cuestion.
	"""
    v_inicial = grafo.obtener_vertice(id_vertice_inicial)
    v_final = grafo.obtener_vertice(id_vertice_final)
    return BFS(grafo, v_inicial).camino_minimo(v_final)
Exemple #7
0
def centralidad(grafo, cantidad):
	"""Calcula los vertices mas "populares"/"centrales" del grafo.
	Calculando los caminos minimos de todos los vertices contra 
	todos los vertices (sin repetir), los vertices mas centrales
	son por los que pasan la mayor cantidad de caminos minimos.
	OBS: Los vertices raiz y destino de los caminos minimos no
	se cuentan en el camino que los une.
	Pre: El grafo existe. La cantidad es un entero mayor a 0.
	"""
	pasadas = {v:0 for v in grafo}
	vertices = grafo.lista_de_vertices()

	for i in xrange(len(vertices)):
		bfs = BFS(grafo, vertices[i])
		for j in xrange(i+1, len(vertices)):
			# [1:-1] porque no cuenta la raiz y destino
			for v in bfs.camino_minimo(vertices[j])[1:-1]:
				pasadas[v] += 1

	return _primeros_k_max(pasadas, cantidad)
Exemple #8
0
def centralidad(grafo, cantidad):
    """Calcula los vertices mas "populares"/"centrales" del grafo.
	Calculando los caminos minimos de todos los vertices contra 
	todos los vertices (sin repetir), los vertices mas centrales
	son por los que pasan la mayor cantidad de caminos minimos.
	OBS: Los vertices raiz y destino de los caminos minimos no
	se cuentan en el camino que los une.
	Pre: El grafo existe. La cantidad es un entero mayor a 0.
	"""
    pasadas = {v: 0 for v in grafo}
    vertices = grafo.lista_de_vertices()

    for i in xrange(len(vertices)):
        bfs = BFS(grafo, vertices[i])
        for j in xrange(i + 1, len(vertices)):
            # [1:-1] porque no cuenta la raiz y destino
            for v in bfs.camino_minimo(vertices[j])[1:-1]:
                pasadas[v] += 1

    return _primeros_k_max(pasadas, cantidad)
Exemple #9
0
def main():
    # print(noOfTestCases)
    # print(noOfRules)
    # print(noOfStates)
    # print(states)
    # print(rules)
    # for test in testCases:
    #     print(test.source, end=",")
    #     print(test.destination)
    # print(transitionTable)
    BFS()
Exemple #10
0
def main():
    n = int(input("Enter the number of node"))
    e = int(input("Enter the number of edge"))
    #src=int(input("Enter Soource"))
    g1 = Graph(n, "al")

    for i in range(e):
        a, b = input().split()
        a = int(a)
        b = int(b)
        g1.insert(a, b)
    bfs = BFS(n, g1)
    visited = bfs.visited
    ans = 0
    for i in range(n):
        if visited[i] == 0:
            ans += 1
            bfs.bfs(i)

    print("Number of Comp : ", ans)
Exemple #11
0
    def run(self):
        self.listenConfiguration()
        algorithm = self.algorithmType.get()
        if (algorithm == "A*"):
            AStarAlgorithm = AStar(self.map,self.startGrid,self.targetGrid,self.isPathVisible,self.screen)
            return AStarAlgorithm.run()

        elif (algorithm == "BFS"):
            BFSAlgorithm = BFS(self.map,self.startGrid,self.targetGrid,self.isPathVisible,self.screen)
            return BFSAlgorithm.run()

        elif (algorithm == "DFS"):
            DFSAlgorithm = DFS(self.map, self.startGrid, self.targetGrid, self.isPathVisible,self.screen)
            return DFSAlgorithm.run()

        elif (algorithm == "Dijkstra"):
            DijkstraAlgorithm = Dijkstra(self.map, self.startGrid, self.targetGrid, self.isPathVisible,self.screen)
            return DijkstraAlgorithm.run()

        else:
            return
def test_bfs(tests):
    bfs = BFS()

    for t in tests:
        bfs.test(t[0], t[1])

    bfs.runTests()
    print_break()
def main():
    for line_number, element in enumerate(get_input("input.txt")):
        print(element)
        board_size = int(element[0])
        board_puzzle_config = element[3]
        board_initial_depth = 1
        max_depth = int(element[1])
        max_length = int(element[2])

        board = Board(board_size, board_puzzle_config, None, 0,
                      board_initial_depth)

        # DFS
        dfs = DFS(board, max_depth, line_number)
        dfs.search()

        # BFS
        bfs = BFS(board, max_length, line_number)
        bfs.search()

        # A*
        astar = ASTAR(board, max_length, line_number)
        astar.search()
Exemple #14
0
    def find_path(self):
        maze = self.read_maze(self.filename)
        #maze.write_svg('read.svg')

        if (self.type == 'bfs'):
            algorythm = BFS(maze)
        elif (self.type == 'dfs'):
            algorythm = DFS(maze)
        elif (self.type == 'idfs'):
            algorythm = IDFS(maze)
        else:
            sys.exit('Wrong algorythm type, is: ' + self.type +
                     ', should be: bfs or dfs or idfs, check spelling')

        time_start = timer()
        path, state_visited = algorythm.find_path()
        time_stop = timer()
        time_passed = time_stop - time_start
        if self.print == True:
            maze.write_svg(self.filename[0:-4] + '_' + self.type + '.svg',
                           path)

        return time_passed, state_visited
Exemple #15
0
def main():
    global results
    input = sys.argv[1]
    output = sys.argv[2]
    world = Graph(str(input))
    for sink in world.sink:
        answer = MinCut(world, world.source, sink, BFS())
        results.append(answer)
        world.reset()
    final_result = corteST(results)
    vs = getSet(final_result, world)
    if len(vs) == 0 or len(vs) == world.vertex:
        vs = set(dict.fromkeys(final_result[1]))
    comprimento_s = len(vs)
    write_output(comprimento_s, vs, final_result[2], output)
Exemple #16
0
def identify_pathfinder(name):
    if name == "Depth-First Search":
        solver = DFS(grid, int(start_x), int(start_y), int(end_x), int(end_y),
                     screen)
        solver.agenda.append(grid[int(start_x)][int(start_y)])
    elif name == "Breadth-First Search":
        solver = BFS(grid, int(start_x), int(start_y), int(end_x), int(end_y),
                     screen)
        solver.agenda.append(grid[int(start_x)][int(start_y)])
    elif name == "Dijkstra's Algorithm":
        solver = Dijkstra(grid, int(start_x), int(start_y), int(end_x),
                          int(end_y), screen)
    elif name == "A* Pathfinder":
        solver = AStarPathfinder(grid, int(start_x), int(start_y), int(end_x),
                                 int(end_y), screen)
    return solver
Exemple #17
0
    def eventLoop(self, screen):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                pg.quit()
                sys.exit()
            if event.type == pg.MOUSEWHEEL:
                self.setZoom(event.y)
                self.clearScreen(screen)

            if event.type == pg.MOUSEBUTTONDOWN:
                mouse_pos = event.pos  # gets mouse position
                for btn in self.buttons:
                    if btn.wasPressed(event):
                        if btn.text.lower() == "dfs":
                            graph = self.objects[0]
                            dfs = DFS(graph)
                            dfs.run(screen)
                        if btn.text.lower() == "bfs":
                            graph = self.objects[0]
                            dfs = BFS(graph)
                            dfs.run(screen)
Exemple #18
0
def main():
    board = Board()
    a = ASTAR(board)
    b = BFS(board)
    for i in range(3):
        print("________________________________trial_",i+1,"_______________________________")
        print("initial state:")
        board.scramble()
        board.print()
        
        
        print("astar solution:")
        temp = a.search(board)
        board.path(temp)[goal]._board.print()
        print(board.path(temp)[path])
        print()
        
        print("bfs solution:")
        temp = a.search(board)
        board.path(temp)[goal]._board.print()
        print(board.path(temp)[path])
        print()
Exemple #19
0
def main():

    # reading input file while ignoring empty lines
    with open("input.txt") as f:
        lines = [line.rstrip('\n') for line in open('input.txt')]
    # adding information only
    info = []
    for i in range(len(lines)):
        if lines[i] != '':
            info.append(lines[i])

    algo_type = info[0]
    board_size_str = info[1]
    initial_state_with_dashes = info[2]
    initial_state = initial_state_with_dashes.split("-")

    # create the relevant algorithm
    if algo_type == "1":
        algorithm = IDS()
    elif algo_type == "2":
        algorithm = BFS()
    else:
        algorithm = AStar()

    size = int(board_size_str)
    # creating #board-size empty arrays
    arr = [[] for i in range(int(size))]

    # fill the array with the given values
    j = 0
    for i in range(int(size)):
        for k in range(int(size)):
            arr[i].append(int(initial_state[j]))
            j += 1

    # creating the board instance
    board = Board(arr, size)
    # solve
    algorithm.run(board)
Exemple #20
0
 def breadthFirstSearch(self):
     print("\nIniciando Busqueda Breadth First Search")
     print("------------------------------------------")
     bsf = BFS(self.listNodes, self.searched)
     bsf.search()
Exemple #21
0
G.add_node('v')
G.add_node('w')
G.add_node('x')
G.add_node('y')

G.add_edge('v', 'r')
G.add_edge('r', 's')
G.add_edge('s', 'w')
G.add_edge('w', 't')
G.add_edge('w', 'x')
G.add_edge('x', 't')
G.add_edge('x', 'u')
G.add_edge('x', 'y')
G.add_edge('t', 'u')
G.add_edge('y', 'u')

H = BFS(G, 's')

labels = {}
for v in H.nodes():
    labels[v] = H.node[v]['depth']

pos = nx.spring_layout(H)
nx.draw(H, pos)
# pos = nx.spring_layout(G)
# nx.draw(G, pos)
#nx.draw_networkx_labels(H, pos, labels)
#nx.draw_networkx_edges(H, pos)

plt.show()
	
	loop_graph = graph.checkConstraints(loop_graph, line[i], int(line[i][5]));

	#Associate child nodes to the respective parent (it is double because the inverted route
	for j in range(0, 2*mapas.numConnects - graph.count):
		loop_graph = graph.MakeGraph(j, loop_graph[j].arrival, loop_graph)
	
	# Depth First Search Algorithm
# 	dfs = DFS();
# 	dfs.limitCost = graph.limitCost;
# 	dfs.limitTime = graph.limitTime;
# 	startingNode = dfs.dfs_initState(loop_graph, line[i][1], int(line[i][3]))
# 	solution = dfs.dfs_search(startingNode, line[i][2])

	# Breadth First Search Algorithm
	bfs = BFS();
	bfs.limitCost = graph.limitCost;
	bfs.limitTime = graph.limitTime;
	startingNode = bfs.bfs_initState(loop_graph, line[i][1], int(line[i][3]))
	solution = bfs.bfs_search(startingNode, line[i][2])

# 	aStar = A_star();
# 	aStar.min = line[i][4];
# 	aStar.limitCost = graph.limitCost;
# 	aStar.limitTime = graph.limitTime;
# 	startingNode = aStar.aStar_initState(loop_graph, line[i][1], int(line[i][3]))
# 	solution = aStar.aStar(startingNode, line[i][2])
	
	# Write to the .sol text file
	if not solution:
		solution = str(-1);
Exemple #23
0
from BFS import BFS
from DFS import DFS
from Graph import Graph
from FileReader import FileReader

FILE_NAME = "Graph"

graph = Graph()
file_reader = FileReader()

file_reader.convert_to_graph(FILE_NAME, graph)
BFS = BFS(graph)
BFS.BFS(6)

file_reader.convert_to_graph(FILE_NAME, graph)
DFS = DFS(graph)
DFS.DFS(4)
Exemple #24
0
            j+=1
            if j>4:
                j=0
                i=(i+1)%5
        if j==0 and i==0:
            # print_grid(view) # COMMENT THIS OUT ON SUBMISSION
            newView = State.transform_view(game_state, view)
            mapRep.update(game_state, newView)

            while(len(actions_to_send) == 0 and phase == 'EXPLORE'):
                nextCoord = mapRep.getBestCoord()
                if(nextCoord == None):
                    phase = 'RETRIEVE'
                    break
                else:
                    bfs = BFS(game_state.current_position, nextCoord, mapRep)
                    actions_to_send = list(State.generateActions(game_state.direction, bfs.run_bfs()))
                    
            while(len(actions_to_send) == 0 and phase == 'RETRIEVE'):
                goal = game_state.generateGoldGoal()

                astar = AStar.AStar()
                route = astar.run_astar(game_state, goal)
                actions_to_send = list(State.generateActionsAStar(route))

                phase = 'RETURN'

            while(len(actions_to_send) == 0 and phase == 'RETURN'):
                goal = game_state.generateEndGoal()

                astar = AStar.AStar()
	root=node(warehouse)  # load to the tree
			
	instr=""
	solution=""
	while(1):
		print("\nplease choose the searching method:\nb :BFS\nd :DFS\nu :UCS")
		print("g_1 :Greedy best first search (heuristic 1)") 
		print("g_2 :Greedy best first search (heuristic 2)")
		print("a_1 :A* search (heuristic 1)")
		print("a_2 :A* search (heuristic 2)")
		print("Others :quit")
     
		instr=raw_input(":")
		if instr=="b":
			bfs=BFS(root)
			solution=bfs.search()
		elif instr=="d":
			dfs=DFS(root)
			solution=dfs.search()
		elif instr=="u":
			ucs=UCS(root)
			solution=ucs.search()
		elif instr=="g_1":
			gbfs=GreedyBFS(root,1)  # initialize with heuristic 1
			solution=gbfs.search()
		elif instr=="g_2":
			gbfs=GreedyBFS(root,2)  # initialize with heuristic 2
			solution=gbfs.search(2)
		elif instr=="a_1":
			a_star=A_star(root,1)
Exemple #26
0
    print(f'\nin {(time_ns() - start) / 1000000}ms')
    avg = [np.average(x) for x in all_vals]
    fig, ax = plt.subplots()
    ax.plot(best_vals, label="Max")
    ax.plot(avg, label="Avg")
    plt.xlabel("Generations")
    plt.ylabel("Value")
    legend = ax.legend(loc='lower right')
    plt.show()


r = MazeReader('m4.txt')
mga = MazeGA(r.board, r.steps)
pga = pyeasyga.GeneticAlgorithm(mga,
                                population_size=5000,
                                elitism=True,
                                mutation_probability=.1,
                                generations=50)
pga.fitness_function = fitness_v2
pga.crossover_function = my_crossover

bfs = BFS(mga.maze)
bfs.run()

ast = AStar(mga.maze)
ast.run()

generate_charts(pga)
print_path(mga, pga.current_generation[0], pga.fitness_function)
Exemple #27
0
 def __init__(self, maze:np.ndarray) -> None:
     
     self.__maze = maze
     self.__start_BFS = BFS(maze)
     self.__goal_BFS = BFS(maze)
     self.__intersection_point = None
    root = Node(init_state, 0, list(), None)
    target = Node(goal_state, 0, list(), None)

    while True:
        print("\n-------Menu-------\n"
              "1. BFS\n"
              "2. DFS\n"
              "3. UCS\n"
              "4. A*\n"
              "5. Exit\n")

        opt = int(input())
        algorithm = None

        if opt == 1:
            algorithm = BFS(G, root)
        elif opt == 2:
            algorithm = DFS(G, root)
        elif opt == 3:
            algorithm = UCS(G, root)
        elif opt == 4:
            algorithm = AStar(G, root)
        elif opt == 5:
            break
        else:
            raise AssertionError("Invalid input for algorithm selection!")

        init_time = time()
        found, counter, step = algorithm.run(target)
        elapsed_time = time() - init_time
Exemple #29
0
def read_in_maze(string):
    global running

    def __build_maze(file):
        """
        Builds a node matrix from the input file
        :param file: containing the maze in text form
        :return: the root node of the matrix
        """
        nonlocal maze_xy
        # open file, make a 2d list of each letter
        # with covers try-catch business, '__' prefix is 'private' sort of
        with open(file) as __f:
            for __line in __f:
                # build up a row, then add it to the maze
                __x_tmp = []
                for __char in __line:
                    # don't add newline chars
                    if __char != '\n':
                        __x_tmp.append(__char)
                maze_xy.append(__x_tmp)
        # convert into nodes
        return __build_nodes()

    def __build_nodes():
        """
        Build the matrix of nodes from the maze array
        
        Important design points:
        - conversion starts at index (0, 0) and progresses along a row
          and adds/connects nodes (row+1, col) and (row, col+1) if they are not walls
        - this allows us to hit all the nodes without checking the same node twice and 
          guarantees the that the nodes we are testing are not made already
        - the program will return the node that contains the start, this will act as the 'root' and 
          will consequently lose all islands not reachable from the root
        
        :return: start_node, the node containing the start of the maze, which functions as the 'root' node
        """
        def add_unique_node(row, col):
            """
            Add a new node, if it has not been made already at the given row, col
            or returns the existing node
            :param row: row of the new node
            :param col: col of the new node
            :return: node, the new or already existing node at row, col OR None if the target is a wall
            """
            nonlocal start_node, end_node

            # only add a node if it is not a wall
            if maze_xy[row][col] != wall_indicator:
                # check if there is a node there, add if there is not
                if tmp_node_list[row][col] is None:
                    node = MazeNode(row, col)
                    tmp_node_list[row][col] = node
                else:
                    node = tmp_node_list[row][col]

                # check if this node is the start / end
                if maze_xy[row][col] == start_indicator:
                    node.is_start = True
                    start_node = node
                elif maze_xy[row][col] == end_indicator:
                    node.is_end = True
                    end_node = node

                # return the node for the row, col
                return node
            else:
                return None

        def check_next_node(go_right, current_node):
            """
            Checks if the adjacent node to the right/ below the given node is connected,
            will make a new node there and connect it if it is note present if the space is not a wall
            :param go_right: True if testing the node to the right, False if testing the node below
            :param current_node: the node to start from
            """
            # get delta coordinates for the target node
            delta_col = int(go_right)
            delta_row = int(not go_right)
            # get coordinates of the current node
            current_row, current_col = current_node.coordinates

            # test if in bounds
            if current_row + delta_row < len(
                    maze_xy) and current_col + delta_col < len(maze_xy[0]):
                # add target node
                local_node = add_unique_node(current_row + delta_row,
                                             current_col + delta_col)

                if local_node is None:
                    # node was a wall
                    return
                else:
                    # connect current node and target node
                    current_node.add_local_node(local_node, 1)

        global start_indicator
        nonlocal maze_xy

        # make empty 2d list to temporarily index the nodes
        tmp_node_list = [
            i[:] for i in [[None] * len(maze_xy[0])] * len(maze_xy)
        ]

        # make the node mesh
        for r in range(len(tmp_node_list)):
            for c in range(len(tmp_node_list[r])):
                # add the node
                this_node = add_unique_node(r, c)

                # check if location was not a wall
                if this_node is not None:
                    # check lower
                    check_next_node(False, this_node)
                    # check right
                    check_next_node(True, this_node)

        # start_node, end_node, and tmp_node_list are updated in the helper functions

    def print_maze(maze, sub_list=None, sub_char="."):
        """
        Prints out the maze while substituting the given list of [row, col] locations for the sub_char
        :param maze: the base maze
        :param sub_list: list in form [[row, col], [...], ...] of sub locations
        :param sub_char: char to replace the locations in sub_list with
        :return: Nothing
        """

        for i in range(len(maze)):
            for j in range(len(maze[i])):
                sub = False
                # find if current square should be substituted
                if sub_list is not None:
                    for x, y in sub_list:
                        if i == x and j == y:
                            sub = True
                            break
                if sub and maze[i][j] != start_indicator and maze[i][
                        j] != end_indicator:
                    output_file.write(sub_char)
                elif maze[i][j] == wall_indicator:
                    output_file.write("%")
                else:
                    output_file.write(maze[i][j])
            output_file.write("\n")

    def top_level_search(func):
        """
        Finds the solution to the maze with start location 'root' using DFS, BFS, Greedy, or A*.
        Also prints the solution to the output file.
        
        :param func: the search function to use, the search function should take the root node and end node as an input
        and return the number of steps in the solution and a list of each node visited along the path.
        :return : Nothing
        """
        # get list of path nodes
        num_steps, solution_list = func(start_node, end_node)
        num_expanded = len(solution_list)
        output_file.write(
            "Number of steps in solution: %d \nNumber of nodes expanded: %d \n"
            % (num_steps, num_expanded))

        sub_list = []
        # convert solution to sub points
        for node in solution_list:
            sub_list.append(node.coordinates)

        # print solution
        print_maze(maze_xy, sub_list)

        # reset all nodes back to unvisited
        for node in solution_list:
            node.visited = False

    # the maze will go here, overwrites for each run
    maze_xy = []
    start_node = None
    end_node = None

    # maze txt files must be in the same directory with the given names
    if string == 'O' or string == 'o':
        __build_maze("open maze.txt")
    elif string == 'M' or string == 'm':
        __build_maze("medium maze.txt")
    elif string == 'L' or string == 'l':
        __build_maze("large maze.txt")
    elif string == 'Q' or string == 'q':
        # quit the loop
        running = False
    else:
        print("Please enter O, M, or L")

    if running:
        dfs_obj = DFS()
        bfs_obj = BFS()
        greedy_obj = GREEDY()
        #astar_obj = A_STAR()
        search_function_list = [
            ["\nDepth First Search", dfs_obj.solve_maze],
            ["\nBreadth First Search", bfs_obj.solve_maze],
            #["Greedy Search", greedy_obj.solve_maze],
            #["A* Search", astar_obj.solve_maze]
        ]

        # print the results of each search
        for fname, f in search_function_list:
            output_file.write(fname + ": \n")
            top_level_search(f)
Exemple #30
0
from BFS import BFS 

G = [
    [0, 1, 2, 3, 4, 5, 6, 7],
    [(0, 1), (0, 3), (1, 2), (1, 5), (1, 6), (2, 6), (3, 4), (3, 5), (4, 5), (4, 6), (6, 7)]
    ]

for v in BFS(G, 0):
    print(v)
Exemple #31
0
from BFS import BreadthFirstSearch as BFS
import numpy as np

#10x10 grid
grid = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

start = [0, 0]
goal = [9, 9]

bfs = BFS(grid, start, goal)

while True:
    bfs.find_moves()
    if bfs.find_goal():
        break
    bfs.select_move()

depth_path = bfs.depth_path


#Now to find the best path, we follow the position depths in ascending order
#Only move to positions with a position depth that is one higher than current position
def get_path(pos, path, depth_path):
    #mark current pos as part of the path
    path[pos[0]][pos[1]] = 1
    curr_depth = depth_path[pos[0]][pos[1]]
Exemple #32
0
class Bidirectional_BFS:
    __maze:np.ndarray
    __start_BFS:BFS
    __goal_BFS:BFS
    __intersection_point:tuple

    def __init__(self, maze:np.ndarray) -> None:
        
        self.__maze = maze
        self.__start_BFS = BFS(maze)
        self.__goal_BFS = BFS(maze)
        self.__intersection_point = None
        
    def get_intersection_point(self) -> tuple:
        return self.__intersection_point

    def __intersection_test(self, list1:list, list2:list):
        for node1 in list1:
            for node2 in list2:
                if node1.get_state() == node2.get_state():
                    return node1, node2
        return False

    def search(self ,start:Node, goal:Node)-> str:
        self.__start_BFS.set_frontier(start)
        self.__goal_BFS.set_frontier(goal)

        while len(self.__start_BFS.get_frontier()) and len(self.__goal_BFS.get_frontier()):
            self.__start_BFS.generator(self.__start_BFS.get_frontier().pop(0))
            self.__goal_BFS.generator(self.__goal_BFS.get_frontier().pop(0))

            if self.__intersection_test(self.__start_BFS.get_explored(), self.__goal_BFS.get_explored()):
                self.__intersection_point = self.__intersection_test(self.__start_BFS.get_explored(), self.__goal_BFS.get_explored())
                break
        else:    
            return -1

        path1 = ''
        cuurent = self.__intersection_point[0]
        while cuurent.get_parent():
            path1 += ' ' + cuurent.get_previous_action() 
            cuurent = cuurent.get_parent()

        path2 = ''

        cuurent = self.__intersection_point[1]
        while cuurent.get_parent():
            if cuurent.get_previous_action() == 'L':
                path2 += 'R' + ' '
            elif cuurent.get_previous_action() == 'U':
                path2 += 'D' + ' '
            elif cuurent.get_previous_action() == 'R':
                path2 += 'L' + ' '
            elif cuurent.get_previous_action() == 'D':
                path2 += 'U' + ' '

            cuurent = cuurent.get_parent()
        return (path1[::-1].strip() + ' ' + path2.strip()).strip()
Exemple #33
0
    array = rows.values.tolist()
    r = dimensions[0].values[0]
    c = dimensions[1].values[0]
    return [array,c,r]


data = readFile()
array = data[0]
cols = data[1]
rows = data[2]

puzzle = array
order = 'URDL'

metric = 'Manhattan'
root = Node(puzzle, 0,'',cols,rows)
aStarRoot = AStarNode(puzzle,0,'',metric,cols,rows)
bfsPuzzleSolver = BFS()
dfsPuzzleSolver = DFS()
aStarPuzzleSolver = AStar()

start = time.time()

#bfsPuzzleSolver.solve(root,order)
#dfsPuzzleSolver.solve(root,order)
aStarPuzzleSolver.solve(aStarRoot, metric)

end = time.time()
print('Czas to: ', end - start)

from BFS import BFS
from DFS import DFS
from PRIM import PRIM
from KRUSKAL import KRUSKAL
from DIJKSTRA import DIJKSTRA
from BELLMAN_FORD import BELLMAN_FORD
from Essentials.graph_class import Graph

print(">>> BFS <<<")
#              v  r  s  w  t  x  u  y
adj_matrix = [[0, 1, 0, 0, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0, 0],
              [0, 1, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 1, 1, 0, 0],
              [0, 0, 0, 1, 0, 1, 1, 0], [0, 0, 0, 1, 1, 0, 0, 1],
              [0, 0, 0, 0, 1, 0, 0, 1], [0, 0, 0, 0, 0, 1, 1, 0]]
gBFS = Graph(adj_matrix, ['v', 'r', 's', 'w', 't', 'x', 'u', 'y'])
BFS(gBFS, first=gBFS.v[2], verbose=False, wait=False)
gBFS.print_status()

print("-" * 80)
print("\n>>> DFS <<<")
#              a  b  c  d  e  f  g  h
adj_matrix = [[0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0],
              [1, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]
gDFS = Graph(adj_matrix, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
DFS(gDFS, verbose=False, wait=False)
gDFS.print_status()

print("-" * 80)
print("\n>>> Prim <<<")
 def call_bfs(self):
     dfs = BFS(self.initial_state, self.actions, self.result, self.goal_test, self.get_cost)
     dfs.search_bfs()
Exemple #36
0
from DFS import DFS
from AStar import AStarSearch
import copy

# Initialize items' position, not used for random map
cheese1 = Cheese([1,10])
cheese2 = Cheese([11, 1])
cheese3 = Cheese([4,8])

cheeseList = [cheese1, cheese2, cheese3]
mouse = Mouse([6, 4])
cat = Cat([10, 7])

MAP_HEIGHT = 12
MAP_WIDTH = 12
searchMethod = BFS()


myMap = MapState(None, cheeseList, mouse, cat, MAP_WIDTH, MAP_HEIGHT)
# set random positions
myMap.setInitState()

# ------------------For random map---------------
while(searchMethod.ifCatWin == False):
    print("Generating a random map...")
    searchMethod = BFS()
    # searchMethod = DFS()
    # searchMethod = AStarSearch()
    myMap.setPosInit()
    searchMethod.run(myMap)