def main(): io_handler = IOHandler() input_values = io_handler.read_input_file() strategy = io_handler.get_strategy strategy_param = io_handler.get_strategy_param if strategy == 'bfs': bfs = BFS(strategy_param, input_values) bfs.solve_puzzle() io_handler.write_result_file(bfs.solution_length, bfs.solution_path) io_handler.write_stat_file(bfs.solution_length, bfs.number_of_visited_nodes, bfs.number_of_processed_nodes, \ bfs.recursion_depth, bfs.solution_time) elif strategy == 'dfs': dfs = DFS(strategy_param, input_values) dfs.solve_puzzle() if dfs.solution_length == -1: io_handler.write_wrong_result_file(dfs.solution_length) io_handler.write_wrong_stat_file(dfs.solution_length) else: io_handler.write_result_file(dfs.solution_length, dfs.solution_path) io_handler.write_stat_file(dfs.solution_length, dfs.number_of_visited_nodes, dfs.number_of_processed_nodes,\ dfs.recursion_depth, dfs.solution_time) elif strategy == 'astr': a_star = AStar(strategy_param, input_values) a_star.solve_puzzle() io_handler.write_result_file(a_star.solution_length, a_star.solution_path) io_handler.write_stat_file(a_star.solution_length, a_star.number_of_visited_nodes, \ a_star.number_of_processed_nodes, a_star.recursion_depth, a_star.solution_time) else: print('nieprawdiłowa nazwa strategii')
def find_solution(size=4, number_of_blocks=3, number_of_barricade=0, initial_array=None, goal_array=None, repeat_time=2): results = {} methods = ["bfs", "dfs", "id_dfs", "a_star"] single_result = None for method in methods: results[method] = {} results[method]["times"] = [] results[method]["iterations"] = [] results[method]["steps"] = [] for i in range(repeat_time): print("") # print("BFS") # BFSTool = BFS(size, number_of_blocks, number_of_barricade,initial_array,goal_array) # single_result = BFSTool.bfs() # print_detail(single_result) # results["bfs"]['times'].append(single_result["time"]) # results["bfs"]['iterations'].append(single_result["iterations"]) # results["bfs"]['steps'].append(single_result["steps"]) # # initial_array = single_result["initial_puzzle"].array # goal_array = single_result["final_puzzle"].array # print("DFS") DFSTool = DFS(size, number_of_blocks, number_of_barricade, initial_array, goal_array) single_result = DFSTool.dfs() print_detail(single_result) results["dfs"]['times'].append(single_result["time"]) results["dfs"]['iterations'].append(single_result["iterations"]) results["dfs"]['steps'].append(single_result["steps"]) # # print("ID_DFS") # ID_DFSTool = ID_DFS(size, number_of_blocks, number_of_barricade,initial_array,goal_array) # single_result = ID_DFSTool.id_dfs() # print_detail(single_result) # results["id_dfs"]['times'].append(single_result["time"]) # results["id_dfs"]['iterations'].append(single_result["iterations"]) # results["id_dfs"]['steps'].append(single_result["steps"]) # # print("A*") # A_star_Tool = A_star(size, number_of_blocks, number_of_barricade,initial_array,goal_array) # single_result = A_star_Tool.a_star() # print_detail(single_result) # results["a_star"]['times'].append(single_result["time"]) # results["a_star"]['iterations'].append(single_result["iterations"]) # results["a_star"]['steps'].append(single_result["steps"]) initial_puzzle = single_result["initial_puzzle"] distance = initial_puzzle.manhattan_distance() return distance, results
def TOPOLOGICAL_SORT(V, E): print "===================" color, d, f, time = DFS(V, E) E_transpose = {v: '' for v in V} for v in V: for u in E[v]: E_transpose[u] = E_transpose[u] + v V_sorted = [v for (f, v) in sorted([(f[v], v) for v in V], reverse=True)] print "===================" DFS(V_sorted, E_transpose)
def main(): graph_builder = GraphBuilder("SCC.txt") graph = graph_builder.build_graph() start_node = graph.get_node("1") dfs = DFS(graph, start_node) nodes = dfs.run() for node in nodes: print(node.id)
def use_DFS(): nums = [1, 2, 2, 2, 2, 2, 2, 2, 2, 2] dfs = DFS(10, nums, 3.5, False) start = time.time() all_solutions = dfs.get_solutions() end = time.time() if len(all_solutions) == 0: print("no solutions were found") for solution in all_solutions: print(solution) print(end - start)
def main(file, mode): with open(file) as maze_file: maze_data = json.load(maze_file) maze = maze_data["maze"] initial_state = maze_data["initial_state"] initial_state = Node(initial_state[0], initial_state[1]) goal_states = maze_data["goal_states"] dfs = DFS("DEPTH-FIRST SEARCH", maze, initial_state, goal_states) dfs.execute(mode) bfs = BFS("BREADTH-FIRST SEARCH", maze, initial_state, goal_states) bfs.execute(mode) ids = IDS("ITERATIVE DEEPENING SEARCH", maze, initial_state, goal_states) ids.execute(mode) ucs = UCS("UNIFORM-COST SEARCH", maze, initial_state, goal_states) ucs.execute(mode)
def start(self): self.started = True self.homePage = False self.startButton.pack_forget() self.initialBoard = self.board self.backButton.pack(side=LEFT) self.buttons = [] for i in range(0,4): button = Button(self.ButtonsFrame,bg='white',fg='#444488',font=('Times 18 bold')) self.buttons.append(button) self.buttons[i].pack(side=LEFT,expand=YES,fill=BOTH) initialState = State(self.board,'',None) self.buttons[0].config(text=' DFS ',command =lambda: self.solveButtonAction(DFS(initialState))) self.buttons[1].config(text=' BFS ',command =lambda: self.solveButtonAction(BFS(initialState))) self.buttons[2].config(text='A* (Euclidean)',command =lambda: self.solveButtonAction(Euclidean(initialState))) self.buttons[3].config(text='A* (Manhattan)',command =lambda: self.solveButtonAction(Solver(initialState))) self.nextButton = Button(self.ButtonsFrame,bg='white',fg='#444488',text=' Next >>',font=('Times 18 bold'),command =lambda:self.nextButtonAction()) self.previousButton = Button(self.ButtonsFrame,bg='white',fg='#444488',text='<< Previous ',font=('Times 18 bold'),state=DISABLED,command =lambda:self.previousButtonAction()) self.endButton = Button(self.ButtonsFrame,bg='white',fg='#444488',text=' END ',font=('Times 18 bold'),command =lambda:self.endButtonAction()) self.beginButton = Button(self.ButtonsFrame,bg='white',fg='#444488',text=' BEGINNING ',font=('Times 18 bold'),command =lambda:self.beginButtonAction()) self.costLabel = Label(self.labelsFrame,bg='white',fg='#888888') self.exploredLabel = Label(self.labelsFrame,bg='white',fg='#888888') self.depthLabel = Label(self.labelsFrame,bg='white',fg='#888888') self.timeLabel = Label(self.labelsFrame,bg='white',fg='#888888') self.stepsLabel = Label(self.labelsFrame,bg='white',fg='#444488') self.backButton.config(state="normal") self.startHomePage()
def handle_merge_check(co, handle, point, txn): change = handle_last_modified(co, co.contents, handle, point, txn) if change is None: return None hcache = {} cDFS = DFS(_merge_check_deps, [co, handle, txn, hcache]) cDFS.search(change) ordering = cDFS.result() for point in ordering: hinfo = hcache[point] if not hinfo.has_key('handle') and len(hinfo['precursors']) > 1: raise HistoryError, 'cannot automatically merge changes' return
def ConnectedComponents(mat): count = 0 visited = [] for i in range(len(mat)): if not i in visited: visited += DFS(mat, i) count += 1 return count, set(visited)
def connectedComponent(g): nodes = g.keys() cc = [] for n in nodes: if not isAlreadyVisited(n, cc): c = DFS(n, g) cc.append(c) return cc
def sync_history(co, point, txn, cache=dict()): named, modified, manifest = [], [], {} sync_dfs = DFS(_history_deps, [co, txn, cache]) sync_dfs.search(point) points = sync_dfs.result() for npoint in points: named, modified, unnamed, unmodified = \ _sync_history(co, npoint, txn, cache=cache) unchecked = dict.fromkeys(unnamed) for handle in named: if handle in unchecked: continue _verify_manifest(co, handle, npoint, txn) co.changesdb.put(binascii.hexlify(npoint), '', txn=txn) return named, modified
def DFSAlgo(state): dfs = DFS() dfs.init() start = timeit.default_timer() dfsAlgo = dfs.doDFS(state, "1,2,5,3,4,0,6,7,8") path = dfsAlgo[0][0] depth = dfsAlgo[0][1] explored = dfsAlgo[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(','))
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 dfs_trainNtest(dfs_y_train, dfs_y_test): model = DFS(in_dim = vocab_size, num_classes = 2, lambda1 = 0.04) # print(dfs_y_train) print(X_train) # prints model.fit(X_train, dfs_y_train, epochs = 10, batch_size = 100, validation_data = [X_test, dfs_y_test]) print(model.accuracy(X_test, dfs_y_test)) print(model.write_predictions("dfs_results.txt", X_test, dfs_y_test))
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()
def base_trials(self, trials, test_cases, target_numbers, debug): solved = 0 off = 0 time_solved = 0 time_unsolved = 0 for i in range(trials): if i % (trials / 20) == 0: print(str(i * 100 / trials) + "%") start = time.clock() nums = test_cases[i] target = target_numbers[i] dfs = DFS(len(nums), nums, target, True) (closest, solution) = dfs.get_solutions() elapsed = time.clock() - start if closest == target: time_solved = time_solved + elapsed solved = solved + 1 else: time_unsolved = time_unsolved + elapsed off = off + abs(target - closest) if debug: print("Closest: " + str(closest) + "( " + str(abs(target - closest)) + " off)") print(solution) print("") print("Percentage Solved: " + str(100 * solved / trials) + "%") print("Average Error: " + str(off / trials)) print("Total Time: " + str(time_solved + time_unsolved)) if solved == 0: print("Average Time for Solved Case: " + str(0)) else: print("Average Time for Solved Case: " + str(time_solved / solved)) if trials - solved == 0: print("Average Time for Unsolved Case: " + str(0)) else: print("Average Time for Unsolved Case: " + str(time_unsolved / (trials - solved)))
def TopSort(mat): n = len(mat[0]) visited = [False for i in range(n)] order = [0 for i in range(n)] i = n - 1 for j in range(n): if visited[j]: continue visitedNodes = DFS(mat, j, []) visited[j] = True for node in visitedNodes: order[i] = node i -= 1 return list(reversed(order))
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
def test_basic(self): graph = { 'a': ['b', 'd'], 'b': ['e'], 'c': ['e', 'f'], 'd': ['b'], 'e': ['d'], 'f': ['f'] } ans, te, be, fe, ce = DFS(graph) for key in graph: self.assertEqual(key in ans, True) self.assertEqual(te, ['ab', 'be', 'ed', 'cf']) self.assertEqual(be, ['db']) self.assertEqual(fe, ['ad']) self.assertEqual(ce, ['ce'])
def test_basic2(self): graph = { 'a': ['b', 'c'], 'b': ['d'], 'c': ['d'], 'd': ['e', 'g'], 'e': ['f', 'g'], 'f': ['b'], 'g': [] } ans, te, be, fe, ce = DFS(graph) for key in graph: self.assertEqual(key in ans, True) self.assertEqual(te, ['ab', 'bd', 'de', 'ef', 'eg', 'ac']) self.assertEqual(be, ['fb']) self.assertEqual(fe, ['dg']) self.assertEqual(ce, ['cd'])
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)
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
N.B. a/b corresponds to the number of nodes where the setup in <a> has domain_values = ['knight', 'king'] and the setup in <b> has domain_values = ['king', 'knight']. """ print("Grid:\n", Setup.grid) print(f"(Size {Setup.grid_size})") dfs = DFS() node = dfs.search() grid = Grid(np.ndarray((Setup.grid_size, Setup.grid_size), dtype=str)) for point, value in node.state.assignment.items(): grid[point] = ['O', 'K'][value == 'knight'] print("Grid:\n", grid)
def depthFirstSearch(self): print("\nIniciando Busqueda Depth First Search") print("------------------------------------------") dfs = DFS(self.listNodes, self.searched) dfs.search()
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)
#now handle NaN's data = data.fillna(0) #do dataframe normalization to 0-1 range X = (data - data.min()) / (data.max() - data.min()) #NaN's can creep back if data.max() - data.min() = 0 X = X.fillna(0) #do test train split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) num_classes = len(y[0]) input_dim = len(X.columns) #actually do neural net training lambda1s = [1, 10] models = [] for lmda in lambda1s: print("Training on lambda = " + str(lmda)) model = DFS(input_dim, num_classes, hidden_layers=[1024, 256], lambda1=lmda, alpha1=0.001, learning_rate=0.01) model.fit(X_train, y_train, batch_size=100, epochs=5, validation_data=[X_test, y_test]) models.append(model)
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) solution=a_star.search() elif instr=="a_2": a_star=A_star(root,2)
def handle_contents_at_point(co, handle, point, txn, dcache=None, replayfunc=replay): if dcache is None: dcache = {} #staticinfo = bdecode(co.staticdb.get(handle, txn=txn)) staticinfo = db_get(co, co.staticdb, handle, txn) if staticinfo['type'] != 'file': raise ValueError, 'Expected type \"file\", got type \"%s\"' % \ (staticinfo['type'],) change = handle_last_modified(co, co.contents, handle, point, txn) if change is None: return None hcache = {} cache = _mini_dag_refcount(co, handle, change, txn, info_cache=hcache) hfile = open(path.join(co.cpath, binascii.hexlify(handle)), 'rb') #hfile = open(path.join(co.cpath, 'diffs'), 'rb') cDFS = DFS(_content_deps, [hcache]) cDFS.search(change) ordering = cDFS.result() for point in ordering: hinfo = hcache[point] if hinfo['handle'].has_key('delete'): # Pick contents of an ancestor, doesn't really matter cache[point]['info'] = cache[hinfo['precursors'][0][0]].copy() cache[point]['info']['delete'] = hinfo['handle']['delete'] # put together the precursor list and decrement refcounts precursors = [] for pre, foo in hinfo['precursors']: precursors.append(cache[pre]['info']) cache[pre]['refcount'] -= 1 if cache[pre]['refcount'] == 0: del cache[pre] if hinfo['handle'].has_key('delete'): # This has to be done after decrementing refcounts, whereas the # content setting has to be done before. continue # read the diff if dcache.has_key(point): diff = dcache[point] else: diff = _read_diff(hinfo, hfile) if diff is None: if len(hinfo['precursors']) > 1: raise HistoryError, 'cannot automatically merge changes' raise HistoryError, 'change with no diff' diff = bdecode(zlib.decompress(diff)) # finally, get the contents cache[point]['info'] = _handle_contents_at_point(point, hinfo, precursors, diff, replayfunc=replayfunc) hfile.close() cache[change]['info']['type'] = staticinfo['type'] return cache[change]['info']
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)
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)
np.savetxt("coverturaDfs8.txt",coverturaPixelsDfs8,delimiter=',') with open("coverturaDfs8.txt","wb") as f: writer = csv.writer(f) writer.writerows(coverturaPixelsDfs8) matrizFromImageForDfs = c2 g = copy.deepcopy(matrizFromImageForDfs) matrizVacia = matricesVacias(0,0) matrizFin = matrizVacia.defineFin(fin,matrizFromImageForDfs) print(matrizFin) wf = WaveFront(matrizFin,filas,columnas) matrizWithWaveFront = wf.aplyWaveFrontToMatrix() matrizInicioFin = matrizVacia.definirOrigenFin(inicio,fin,matrizWithWaveFront) print(matrizInicioFin) df = DFS(matrizInicioFin,columnas,filas) coverturaDFS = df.getCoverRouteWitSeed() i = 0 dupe = False while i < len(coverturaDFS)-1: if coverturaDFS[i] == coverturaDFS[i+1]: del coverturaDFS[i] else: i += 1 graphicsDFS = Graphics(g) graphicsDFS.printCovertura(coverturaDFS) (visit,revisit) = graphicsDFS.counter() twist = graphicsDFS.numberOfTwist(coverturaDFS) with open ("propiedesDfs.txt","wb") as f: f.write("visitas: {visitas} re visitas : {revisitas} giros {giros}".format(visitas = visit,revisitas=revisit, giros = twist))
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 if found: print("Match found!\n"