def find_game_mode(self, game_mode): if game_mode == DFS_MODE: return DFS.DFS() elif game_mode == A_STAR_MODE: return A_STAR.A_STAR() elif game_mode == BFS_MODE: return BFS.BFS() raise Exception( "Attention: Only DFS and A-STAR modes are available currently.")
def getAlgo(type, Matrix, startX, startY, n, grid, size): if type == "DFS": print("DFS") result = DFS(Matrix, startX, startY, n - 1, n - 1, grid, n, size) return result if type == "BFS": return BFS(Matrix, startX, startY, n - 1, n - 1, grid, n, size) if type == "AStar": return AStar(Matrix, startX, startY, n - 1, n - 1, grid, n, size, "Manhattan")
def aplica_largura(): if sys.version_info[0] < 3: pathDoArquivo = tk.Open().show() else: pathDoArquivo = filedialog.askopenfilename() G = nx.read_gexf(pathDoArquivo) G = bfs.BFS(G, G.nodes()[0]) pathDoArquivo = pathDoArquivo.replace(".gexf", "_BFS.gexf") nx.write_gexf(G, pathDoArquivo) nx.draw(G) plt.show()
def run(): global flag, p, cost gui.redraw(height, width, cellSize, initializer.gridworld) if algoflag == 1: path = BFS().search(initializer.gridworld, start, goal) elif algoflag == 2: path = Dijkstra().search(initializer.gridworld, start, goal) else: path = AStar().search(initializer.gridworld, start, goal) if flag == False: if path == True and initializer.gridworld.cells[goal[0]][ goal[1]].visited == False: if algoflag == 1: BFS().search(initializer.gridworld, start, goal) elif algoflag == 2: Dijkstra().search(initializer.gridworld, start, goal) else: AStar().search(initializer.gridworld, start, goal) else: if algoflag == 1: p, explored, cost = BFS().makepath(initializer.gridworld) elif algoflag == 2: p, explored, cost = Dijkstra().makepath(initializer.gridworld) else: p, explored, cost = AStar().makepath(initializer.gridworld) flag = True gui.redraw(height, width, cellSize, initializer.gridworld) else: print('Path found!') print('The path is:', p) print('The cost is:', cost[goal]) print('GUI will exit in:', t, 'seconds') time.sleep(t) sys.exit() root.after(1, run)
def p1(select): start = problem1.InitialState() if select == "a": print(BFS.BFS(start, problem1), "BFS") if select == "b": goal = problem1.GoalState() print(bidirectional.bidirectional(start, goal, problem1), "bidirectional") if select == "c": print(dfs.DFS(start, problem1), "DFS")
def solver_3(self, the_map): temp_init = convert_zero_to_blank(copy.deepcopy(the_map)) temp_win = convert_zero_to_blank(copy.deepcopy(self.win_map)) stateList = transistion(temp_win) state = BFS(temp_init, temp_win, stateList=stateList) path = state.solveProblemByBFS(temp_win) route = [] # path的最后一个元素为程序求解的运行时间 run_time = path.pop() # path的路径是相反的,记得要倒叙遍历 for mat in reversed(path): route.append(convert_blank_to_zero(mat)) return route, run_time
def neuralDistances(state, action): factors = gatherFactors(state.generateSuccessor(0, action)) features = util.Counter() pacman = factors["pacman_loc"] for i in range(len(factors["ghost_locs"])): if factors["scared"][i] > 0: features["ghost " + str(i) + " scared"] = len(BFS.BFS(pacman, factors["ghost_locs"][i], state)) features["ghost " + str(i) + " timer"] = factors["scared"][i][1] else: features["ghost " + str(i)] = len(BFS.BFS(pacman, factors["ghost_locs"][i], state)) for i in range(len(factors["capsule_locs"])): features["capsule" + str(i)] = len(BFS.BFS(pacman, factors["capsule_locs"][i], state)) food_groups = BFS.coinGroup3s((int(pacman[0]), int(pacman[1])), state) while len(food_groups) < 3: food_groups.append((0, 0)) for i in range(3): features["food group " + str(i) + " dist"] = food_groups[i][0] features["food group " + str(i) + " size"] = food_groups[i][1] return features
def p2(select): start = problem2.InitialState() if select == "a": print(BFS.BFS(start, problem2), "BFS") if select == "b": print(dfs.DFS(start, problem2), "DFS") if select == "c": print(dfs.LDFS(start, problem2, 15), "LDFS") if select == "d": print(Astar.Astar(start, problem2), "A*")
def FirstPlot(): algo_name = "BFS search" input_data = [] exec_time = [] for n in range(100, 1100, 100): graphList = [] graph = BFS.Graph(g=graphList) vertexList = [] BFS.createGraph(graph, vertexList, n) vertexNum = random.randint(0, n - 1) start_time = time.clock() BFS.BFS(graph, vertexList[vertexNum]) end_time = time.clock() exec_time.append((end_time - start_time) * 1000) input_data.append(n) CreatePlot(input_data, exec_time, algo_name)
def getNext(graph, vertices): bfsList = [BFS(graph, vertex) for vertex in vertices] V = graph.numOfVertices() maxDist = 0 res = -1 for i in range(V): dist = 0 isConnected = True for bfs in bfsList: if not bfs.hasPathTo(i): isConnected = False dist += bfs.distanceTo(i) if isConnected and dist > maxDist: if i not in vertices: maxDist = dist res = i print "%d with distance %d" % (res, maxDist) distList = [bfs.distanceTo(res) for bfs in bfsList] print distList return res
def getFeatureCapsule(factors, features, pacman, state, old_pac_pos=None): capsules = [] for i in range(len(factors["capsule_locs"])): capsules.append([ float(len(BFS.BFS(pacman, factors["capsule_locs"][i], state))), factors["capsule_locs"][i] ]) capsules.sort() if len(capsules) > 0: farthest_consideration = 15 for i in range(min(int(capsules[0][0]), farthest_consideration)): features["closest-capsule-" + str(farthest_consideration - i) + "-away"] = 1 if old_pac_pos is not None: features["towards-capsule"] = \ directional(factors["capsule_locs"][0], old_pac_pos, pacman, state)
def runSearchAlgorithm(self, alg): if(self.startNode == None or self.endNode == None): return if alg.get() == "DFS": dfs = DFS(self.g,self.startNode, self.endNode, GUI = self) dfs.run() elif alg.get() == "BFS": bfs = BFS(self.g,self.startNode, self.endNode, GUI = self) bfs.run() elif alg.get() == "A*": a_star = A_Star(self.g, self.startNode, self.endNode, GUI = self) a_star.run() elif alg.get() == "WA*": w = simpledialog.askinteger("Input", "Choose a weight for WA*", parent=self.win, minvalue=0, maxvalue=10000) wa_star = WA_Star(self.g, self.startNode, self.endNode, weight = w, GUI = self) wa_star.run() else: dijkstra = Dijkstra(self.g, self.startNode, self.endNode, GUI=self) dijkstra.run()
def distanceDiff(cur_state, next_state, obj_loc, ghosts=False, scared_list=None): diff = [] cur_pac = cur_state.getPacmanPosition() next_pac = next_state.getPacmanPosition() # Creates tuple for each object w/ absolute distance and direction for i in range(len(obj_loc)): cur_loc = (int(obj_loc[i][0]), int(obj_loc[i][1])) # Non-scared ghost if ghosts and scared_list[i][0] == 1: # Find all potential moves for ghost legal_ghost_actions = cur_state.getLegalActions(i + 1) legal_ghost_moves = [] for action in legal_ghost_actions: next_state = cur_state.generateSuccessor(i + 1, action) legal_ghost_moves.append(next_state.getGhostPosition(i + 1)) possible_actions = game.Actions.getLegalNeighbors(cur_state.getGhostPosition(i + 1), cur_state.getWalls()) # Find all places the ghost cannot move illegal_moves = [] for possible_action in possible_actions: if possible_action not in legal_ghost_moves: illegal_moves.append(possible_action) path = BFS.BFS(cur_pac, cur_loc, cur_state, illegal_moves) # Finds current distance. Check for edge case where ghost is in house if path is []: cur_dist = len(BFS.BFS(cur_pac, cur_loc, cur_state)) next_dist = len(BFS.BFS(next_pac, cur_loc, cur_state)) # Normal case. Illegal moves excluded else: cur_dist = len(path) next_dist = len(BFS.BFS(next_pac, cur_loc, cur_state, illegal_moves)) else: cur_dist = len(BFS.BFS(cur_pac, cur_loc, cur_state)) next_dist = len(BFS.BFS(next_pac, cur_loc, next_state)) if next_dist - cur_dist >= 0: diff.append((next_dist, 1)) else: diff.append((next_dist, -1)) return diff
def testBFS(self): G = graph() G.addEdge('v', 'r') G.addEdge('s', 'r') G.addEdge('s', 'w') G.addEdge('t', 'w') G.addEdge('x', 'w') G.addEdge('x', 't') G.addEdge('u', 't') G.addEdge('x', 'y') G.addEdge('x', 'u') G.addEdge('y', 'u') BFS.BFS(G, 's') self.assertEqual(G.distance['s'], 0) self.assertEqual(G.distance['w'], 1) self.assertEqual(G.distance['r'], 1) self.assertEqual(G.distance['v'], 2) self.assertEqual(G.distance['t'], 2) self.assertEqual(G.distance['x'], 2) self.assertEqual(G.distance['u'], 3) self.assertEqual(G.distance['y'], 3)
def aplica_todos(): if sys.version_info[0] < 3: pathDoArquivo = tk.Open().show() else: pathDoArquivo = filedialog.askopenfilename() G = nx.read_gexf(pathDoArquivo) M = krl.Kruskal(G) pathDoArquivoNovo = pathDoArquivo.replace(".gexf", "_MST_Kruskal.gexf") nx.write_gexf(M, pathDoArquivoNovo) M = pr.Prim(G, G.nodes()[0]) pathDoArquivoNovo = pathDoArquivo.replace(".gexf", "_MST_Prim.gexf") nx.write_gexf(G, pathDoArquivoNovo) M = bfs.BFS(G, G.nodes()[0]) pathDoArquivoNovo = pathDoArquivo.replace(".gexf", "_BFS.gexf") nx.write_gexf(M, pathDoArquivoNovo) M = dfs.DFS(G, G.nodes()[0]) pathDoArquivoNovo = pathDoArquivo.replace(".gexf", "_DFS.gexf") nx.write_gexf(M, pathDoArquivoNovo) M = dks.Dijkstra(G, G.nodes()[0]) pathDoArquivoNovo = pathDoArquivo.replace(".gexf", "_Dijkstra.gexf") nx.write_gexf(M, pathDoArquivoNovo) M = wp.WelshPowell(G, G.nodes()[0]) pathDoArquivoNovo = pathDoArquivo.replace(".gexf", "_WelshPowell.gexf") nx.write_gexf(M, pathDoArquivoNovo)
def getFeatureGhosts(factors, features, pacman, state, old_pac_pos=None): for i in range(len(factors["ghost_locs"])): # Ghost is scared if factors["scared"][i] > 0: farthest_consideration = 15 cur_distance = min( len(BFS.BFS(pacman, factors["ghost_locs"][i], state)), farthest_consideration) # Distance booleans for j in range(farthest_consideration - cur_distance): features["scared-ghost-" + str(i) + "-" + str(farthest_consideration - j) + "-away"] = 1 # Directional information if old_pac_pos is not None: features["scared-ghost-" + str(i) + "-towards"] = \ directional(factors["ghost_locs"][i], old_pac_pos, pacman, state) # Ghost is not scared # Need to determine if ghost is facing/is a threat to pacman else: # Find all potential moves for ghost legal_ghost_actions = state.getLegalActions(i + 1) legal_ghost_moves = [] for action in legal_ghost_actions: next_state = state.generateSuccessor(i + 1, action) legal_ghost_moves.append(next_state.getGhostPosition(i + 1)) possible_actions = Actions.getLegalNeighbors( state.getGhostPosition(i + 1), state.getWalls()) # Find all non-potential moves for a ghost illegal_moves = [] for possible_action in possible_actions: if possible_action not in legal_ghost_moves: illegal_moves.append(possible_action) # Runs BFS without the spots behind the current ghosts (ghosts can't go backward) farthest_consideration = 15 path = BFS.BFS(pacman, factors["ghost_locs"][i], state, illegal_moves) # Finds current distance. Check for edge case where ghost is in house if path is []: cur_distance = min( len(BFS.BFS(pacman, factors["ghost_locs"][i], state)), farthest_consideration) # Normal case. Illegal moves excluded else: cur_distance = min(len(path), farthest_consideration) # Distance booleans for j in range(farthest_consideration - cur_distance): features["ghost-" + str(i) + "-" + str(farthest_consideration - j) + "-away"] = 1 # Directional information if old_pac_pos is not None: features["ghost " + str(i) + " towards"] = \ directional(factors["ghost_locs"][i], old_pac_pos, pacman, state)
def is_connected(G): BFS(G, v[0]) for i in G: if i.distance == INFINITY: return False return True
def search_for_sequence_merge_all(self, num): """ Try to find a sequence that moves bot from all position to the goal point. :param num: number of iterations :return: a sequence of directions. """ sequence = '' for i in range(num): if self.evaluate(self.prob_matrix) < 30 and self.evaluate( self.prob_matrix) != 1: cells = [] for i in range(self.prob_matrix.shape[0]): for j in range(self.prob_matrix.shape[1]): if self.prob_matrix[i, j] != 0: cells.append([i, j]) cells.sort(key=lambda x: self.prob_matrix[x[0], x[1]]) # direct the largest to the second largest bfs = BFS(self.maze) subseq = directions(bfs.search(cells[-2], cells[-1])) self.perform_moves(subseq) sequence += subseq continue # if there is only one possible position, move it to the goal point and finish elif self.evaluate(self.prob_matrix) == 1: for i in range(self.prob_matrix.shape[0]): for j in range(self.prob_matrix.shape[1]): if self.prob_matrix[i, j] != 0: cell = [i, j] bfs = BFS(self.maze) subseq = directions(bfs.search(cell, self.goal)) self.perform_moves(subseq) sequence += subseq break if self.evaluate(self.prob_matrix) < 80: prob = 0.8 else: prob = 0.01 # choose the direction randomly if random() < prob: rand = random() last_move = sequence[-1] if last_move == 'R': if rand < 0.46: self.prob_matrix = self.right() sequence += 'R' elif rand < 0.64: self.prob_matrix = self.down() sequence += 'D' elif rand < 0.82: self.prob_matrix = self.left() sequence += 'L' else: self.prob_matrix = self.up() sequence += 'U' if last_move == 'L': if rand < 0.46: self.prob_matrix = self.left() sequence += 'L' elif rand < 0.64: self.prob_matrix = self.down() sequence += 'D' elif rand < 0.82: self.prob_matrix = self.right() sequence += 'R' else: self.prob_matrix = self.up() sequence += 'U' if last_move == 'U': if rand < 0.46: self.prob_matrix = self.up() sequence += 'U' elif rand < 0.64: self.prob_matrix = self.down() sequence += 'D' elif rand < 0.82: self.prob_matrix = self.right() sequence += 'R' else: self.prob_matrix = self.left() sequence += 'L' if last_move == 'D': if rand < 0.46: self.prob_matrix = self.down() sequence += 'D' elif rand < 0.64: self.prob_matrix = self.up() sequence += 'U' elif rand < 0.82: self.prob_matrix = self.right() sequence += 'R' else: self.prob_matrix = self.left() sequence += 'L' # choose the direction with most overlapping else: R = self.evaluate(self.right()) L = self.evaluate(self.left()) U = self.evaluate(self.up()) D = self.evaluate(self.down()) m = min([R, L, U, D]) if m == R: self.prob_matrix = self.right() sequence += 'R' if m == L: self.prob_matrix = self.left() sequence += 'L' if m == U: self.prob_matrix = self.up() sequence += 'U' if m == D: self.prob_matrix = self.down() sequence += 'D' return sequence
def getFeatureGhostsSeperate(factors, features, pacman, state): for i in range(len(factors["ghost_locs"])): cur_distance = len(BFS.BFS(pacman, factors["ghost_locs"][i], state)) if factors["scared"][i] > 0: features["ghost " + str(i) + " scared dist"] = min( cur_distance, 7) else: features["ghost " + str(i) + " dist"] = min(cur_distance, 7) for i in range(len(factors["ghost_locs"])): # Ghost is scared if factors["scared"][i] > 0: cur_distance = len( BFS.BFS(pacman, factors["ghost_locs"][i], state)) # Scared ghost values if cur_distance <= 7: features["ghost " + str(i) + " (scared) 7 away"] = 1 if cur_distance <= 5: features["ghost " + str(i) + " (scared) 5 away"] = 1 if cur_distance <= 3: features["ghost " + str(i) + " (scared) 3 away"] = 1 if cur_distance <= 2: features["ghost " + str(i) + " (scared) 2 away"] = 1 if cur_distance <= 1: features["ghost " + str(i) + " (scared) 1 away"] = 1 if cur_distance <= 0: features["ghost " + str(i) + " (scared) 0 away"] = 1 # Ghost is not scared # Need to determine if ghost is facing/is a threat to pacman else: # Find all potential moves for ghost legal_ghost_actions = state.getLegalActions(i + 1) legal_ghost_moves = [] for action in legal_ghost_actions: next_state = state.generateSuccessor(i + 1, action) legal_ghost_moves.append(next_state.getGhostPosition(i + 1)) possible_actions = Actions.getLegalNeighbors( state.getGhostPosition(i + 1), state.getWalls()) # Find all non-potential moves for a ghost illegal_moves = [] for possible_action in possible_actions: if possible_action not in legal_ghost_moves: illegal_moves.append(possible_action) # Runs BFS without the spots behind the current ghosts (ghosts can't go backward) cur_distance = len( BFS.BFS(pacman, factors["ghost_locs"][i], state, illegal_moves)) # Ghost values if cur_distance <= 7: features["ghost " + str(i) + " 7 away"] = 1 if cur_distance <= 5: features["ghost " + str(i) + " 5 away"] = 1 if cur_distance <= 3: features["ghost " + str(i) + " 3 away"] = 1 if cur_distance <= 2: features["ghost " + str(i) + " 2 away"] = 1 if cur_distance <= 1: features["ghost " + str(i) + " 1 away"] = 1
import sys import Start if __name__ == "__main__": print "script_name", sys.argv[0] for i in range(1, len(sys.argv)): print "argument", i, sys.argv[i] print('start initialize') # set the size and density of this matrix size = 10 start = Start.Start(size, 0.3) # start.print_matrix() start.paint_random() # init all the algorithm dfs = DFS.DFS() bfs = BFS.BFS() a_mht = ASTAR_MHT.ASTAR() a_euc = ASTAR_EUC.ASTAR() print('start run') print "DIM, T_DFS, T_BFS, T_MHT, T_EUC" while 1: print size, start = Start.Start(size, 0.3) start.paint_random() while dfs.dfs_route(start.get_matrix(), size)[0] == 0: start.paint_random() # set timer for each algorithm start_time = time.clock() #DFS dfs.dfs_route(start.get_matrix(), size) T_DFS = (time.clock() - start_time)
def search(init, goal): algo = BFS(init, goal, KnuthActions) print(algo.start(verbose=True))
from Node import * from DFS import * from BFS import * from config import originate, target import time if __name__ == '__main__': Node1 = Node(None, originate, 0) Node2 = Node(None, target, 0) DFS = DFS(Node1, Node2, 10, 3) BFS = BFS(Node1, Node2, 10, 3) a_star = a_star(Node1, Node2, 10, 3) #深度优先 start_d = time.time() flag_d = DFS.search() end_d = time.time() cost_d = end_d - start_d #广度优先 start_b = time.time() flag_b = BFS.search() end_b = time.time() cost_b = end_b - start_b if (flag_d): print('The result of DFS') DFS.showLine() print('Spent time:%f s\n\n' % (cost_d)) else: print('error')
##grid1 = gridObj1.generate_grid(n,size) #gridObj2 = GridGenerator(Matrix,"AStar Euclidean") #grid2 = gridObj2.generate_grid(n,size) #gridObj3 = GridGenerator(Matrix,"AStar Manhatten") #grid3 = gridObj3.generate_grid(n,size) #print(Matrix) print("DFS") dfsNodesExp=[] analyseDFS=DFS(Matrix, startX, startY ,n-1,n-1,grid,n,size,p).solve().to_dict() if(analyseDFS['Maze Solved']==True): print("Maze solved DFS: ",analyseDFS['Maze Solved']) plist.append(analyseDFS['Probability']) dfsNodesExp.append(analyseDFS['Nodes Explored']) analyzerObjectDFS.append(analyseDFS) bfsNodesExp = [] analyseBFS = BFS(Matrix, startX, startY, n - 1, n - 1, grid, n, size, p, False).solve().to_dict() if (analyseBFS['Maze Solved'] == True): print("Maze solved DFS: ", analyseBFS['Maze Solved']) bfsNodesExp.append(analyseBFS['Nodes Explored']) analyzerObjectBFS.append(analyseBFS) #nodesExpDFS=[] #nodesExpDFS.append(DFS(Matrix, startX, startY ,n-1,n-1,grid,n,size,p).solve().to_dict()['Nodes Explored']) #print("BFS") #analyzerObjectDFS.append(BFS(Matrix, startX, startY ,n-1,n-1,grid,n,size,p).solve().to_dict()) #print("ASTAR EU") aStarNodesExp = [] analyseAStar = AStar(Matrix, startX, startY ,n-1,n-1,grid,n,size,p,"Euclidean").solve().to_dict() if (analyseAStar['Maze Solved'] == True): print("Maze solved AStar: ", analyseAStar['Maze Solved']) aStarNodesExp.append(analyseAStar['Nodes Explored'])
def test_is_goal(self): self.search = BFS(self.init, self.goal, self.actions) self.assertEqual(self.search.is_goal(self.goal), True)
def setUp(self): self.init = 4 self.goal = 5 self.actions = KnuthActions self.search = BFS(self.init, self.goal, self.actions)
def test_BFS_fail(self): self.init = 0 self.goal = 1 self.search = BFS(self.init, self.goal, self.actions) self.assertEqual(self.search.start(), BFS.error_message)
# -----------------------------------------------------------# # BFS + Shortest Path Algorithm # # # # (C) 2020, LABANI SAID, France # # # # @: [email protected] # # -----------------------------------------------------------# from Graph import * from BFS import * from FindShortestPath import * #Building The Graph Object GraphTest = Graph('TestGraph', 'a,b,c,d,e', ['b,c', 'd,c', 'd,e', 'e', '']) #Creating the BFS Graph (Launching The BFS Algorithm) BFS(GraphTest, GraphTest.Vertices["a"]) #Finding the shortest path from noed "a" to noeud "e" ShortestPath = FindShortestPath(GraphTest.Vertices["a"], GraphTest.Vertices["e"]) #Printing The Shortest Path print(StringPath(ShortestPath))
if (result_node is None): print("No path found using graph search!") else: print("Path:", result_node.path()) print("Path Cost:", result_node.path_cost) print("Solution:", result_node.solution()) print("Nodes searched with graph search:", myGraphSearch.nodesSearched) print("Time Spent with graph search:", myGraphSearch.timeSpent) print("==============") print("BREADTH FIRST SEARCH") # search using BFS Search myBFSSearch = BFS(eight_puzzle) result_node = myBFSSearch.search() if (result_node is None): print("No path found using tree search!") else: print("Path:", result_node.path()) print("Path Cost:", result_node.path_cost) print("Solution:", result_node.solution()) print("Nodes searched with BFS:", myBFSSearch.nodesSearched) print("Time Spent with BFS:", myBFSSearch.timeSpent) print("==============") print("DEPTH FIRST SEARCH") print("\x1b[0;30;41m" + "NOTE -- NEEDS TO BE IMPLEMENTED -- CURRENTLY BFS" +
from BFS import * from Dijkstra import * print("Итоговый путь: ", BFS()) print() print("Итоговый путь: ", Djikstra()) print()
if ButtonRun.pressed(pos): print("Minimum Spanning Tree Is:") print(kruskal.kruskal(Graph)) print("Topological Sort") print(topsort.dfs_topsort(Graph)) print("Breadth First Search") answer = inputbox.ask(window, "Enter Node for BFS") answer = ord(answer) - ord('1') print(BFS.BFS(Graph, Graph.vertexList[answer])) print("Dijkstra Tree") answer = inputbox.ask(window, "Enter Node for Dijkstra Tree") answer = ord(answer) - ord('1') d, p = dijkstra.dijkstra(Graph, Graph.vertexList[answer]) print("Distances:") print d print("Parents:") print p pygame.display.update() #Refreshes the Display