def run_strat_trials(): dimension = int(sys.argv[1]) density = float(sys.argv[2]) flammability = float(sys.argv[3]) strategy = sys.argv[4] cmap = colors.ListedColormap(color_set) norm = colors.BoundaryNorm(range_set, len(color_set)) plt.figure(figsize=(8, 8)) plt.axis('off') mazeTrials = 0 totalSuccesses = 0 while mazeTrials < 10: maze = generate_maze(dimension, density) status, trial_maze = dfs(maze, (0, 0), (dimension - 1, dimension - 1)) while status != 'Success': # generate a valid maze (path from start to goal) maze = generate_maze(dimension, density) status, trial_maze = dfs(maze, (0, 0), (dimension - 1, dimension - 1)) currentIterSuccesses = 0 fireTrials = 0 while fireTrials < 10: fire_maze, fireCoord = init_fire(maze) status, trial_maze = dfs(fire_maze, (0, 0), fireCoord) while status != 'Success': # generate a valid initial fire fire_maze, fireCoord = init_fire(maze) status, trial_maze = dfs(fire_maze, (0, 0), fireCoord) if strategy == 's1': status, fire_result = strategy_one( maze, fire_maze, (0, 0), (dimension - 1, dimension - 1), flammability) elif strategy == 's2': status, fire_result = strategy_two( maze, fire_maze, (0, 0), (dimension - 1, dimension - 1), flammability) elif strategy == 's3': status, fire_result = strategy_three( maze, fire_maze, (0, 0), (dimension - 1, dimension - 1), flammability) if status == 'Escaped': currentIterSuccesses += 1 fireTrials += 1 totalSuccesses += currentIterSuccesses mazeTrials += 1 print(totalSuccesses)
def dfs(path): global files_count files = os.listdir("%s/%s" % (global_path, path)) for file in files: cur_path = "%s%s" % (path, file) if os.path.isdir("%s/%s" % (global_path, cur_path)): dfs("%s/" % cur_path) elif os.path.isfile("%s/%s" % (global_path, cur_path)) and file.split(".")[-1] in suffixes: images_files.append(cur_path) rep = "#%d: %s" % (files_count, cur_path) report_file.write(rep + "\n") print(rep) files_count += 1
def subtourelim(model, where): # this tells Gurobi to stop when it finds an integer solution if where == GRB.Callback.MIPSOL: # make a list of edges selected in the solution delta_dfs = defaultdict(list) for i in N_zero: for j in N_zero: if i != j: x_sol = model.cbGetSolution(x[i, j]) if x_sol > 0.5: delta_dfs[i].append(j) delta_dfs[j].append(i) # Here goes your DFS code for finding connected components # use edges to construct the adjacency lists component = dfs(N_zero, delta_dfs) if (len(component) > 1): # add subtour elimination constraints for every pair of nodes in the # connected components you found. For each component add the cut for k in component: model.cbLazy( quicksum( (quicksum(x[i, j] for j in component[k] if j != i)) for i in component[k]) <= len(component[k]) - 1)
def test_dfs(): xn = np.array([0, 1, 2, 3]) N = 4 X = dfs(xn, N) print(X) x = idfs(X, N) print(x)
def _has_cycle(tree, edge): u = edge[0] v = edge[1] if len(tree) > 0: g = Graph.make_graph(0, tree) visited = dfs(g, u) return v in visited else: return False
def heuristic2(self,game,player,oppo,position): d=dfs(game.board,player) dic=d.run(position) #print "position : ",position #print "player : ",player #print game.showGameState() #print dic val=dic['vertical']*10+dic['horizontal']*5+dic['right_diagonal']*4+dic['left_diagonal']*4 return val
def success_chance( dimension, density ): # runs 100 trials per obstacle density and returns the chance a path can be found from S to G num_success = 0 for i in range(0, 100): maze_trial = generate_maze(dimension, density) # create maze status, maze_copy = dfs(maze_trial, (0, 0), (dimension - 1, dimension - 1)) # run dfs if status == 'Success': num_success += 1 return (num_success / 100)
def test_path_algorithms(): dimension = int(sys.argv[1]) density = float(sys.argv[2]) cmap = colors.ListedColormap(color_set) norm = colors.BoundaryNorm(range_set, len(color_set)) plt.figure(figsize=(8, 8)) plt.axis('off') maze = generate_maze(dimension, density) # generate maze # run each algorithm on maze and time them start_time = time.time() status, astar_maze, num_explored_nodes = astar( maze, (0, 0), (dimension - 1, dimension - 1)) end_time = time.time() print(status) print(end_time - start_time) print(num_explored_nodes) start_time = time.time() status, bfs_maze, num_explored_nodes = bfs(maze, (0, 0), (dimension - 1, dimension - 1)) end_time = time.time() print(status) print(end_time - start_time) print(num_explored_nodes) start_time = time.time() status, dfs_maze = dfs(maze, (0, 0), (dimension - 1, dimension - 1)) end_time = time.time() print(status) print(end_time - start_time) # plot each result and save as image plt.imshow(astar_maze, cmap=cmap, norm=norm) plt.savefig('astar_maze.jpg') plt.imshow(bfs_maze, cmap=cmap, norm=norm) plt.savefig('bfs_maze') plt.imshow(dfs_maze, cmap=cmap, norm=norm) plt.savefig('dfs_maze')
def main(): fileNames = [ "graph1.txt", "graph2.txt", "graph3.txt", "graph4.txt", "graph5.txt" ] file = open(fileNames[0], "r") i = 0 #Create adjacency matrix am = adjacencyMatrix() for line in file: if i == 0: #First row in file contains number numVertices = int(line) am.create(numVertices) else: dest, source = line.split() am.addEdge(dest, source) i += 1 am.display() ''' i=0 #Create adjacency list al = adjacencyList() for line in file: if i == 0: #First row in file contains number numVertices = int(line) else: dest, source = line.split() al.addEdge(dest, source) i+=1 al.display() ''' #Searches d = dfs(numVertices, am) visited = d.searchRecursive(0) print(visited) '''
import chess, chess.pgn, sys from dfs import * # Load file fil = open(sys.argv[1], 'r') root = chess.pgn.read_game(fil) fil.close() # Loop through games visitedNodes = set() currentNode = root counter = 1 fil = None if '-o' in sys.argv: fil = open(sys.argv[1] + '.split', 'w') for node in filter(lambda x: x.is_end(), dfs(root)): game = chess.pgn.Game.from_board(node.board()) if '-o' not in sys.argv: # Make different pgn file for each line fil = open(sys.argv[1] + '-' + str(counter), 'w') counter += 1 if '-h' in sys.argv or '-o' not in sys.argv: # Include repeated header print(game, file=fil) else: # Skip headers exporter = chess.pgn.FileExporter(fil, headers=False) game.accept(exporter) print(file=fil) # Print new line
print("---- BFS -----") node, tree = bfs(State2((3, 3, 1), (3, 3, 1), "Start")) print("- Tree -") tree.print_tree() if node is not None: path = find_path(node) print("- Solution -") print_path(path) else: print("- No Solution -") print('\n\n\n\n\n\n') print("---- DFS -----") node, tree = dfs(State2((3, 3, 1), (3, 3, 1), "Start")) print("- Tree -") tree.print_tree() if node is not None: path = find_path(node) print("- Solution -") print_path(path) else: print("- No Solution -") print('\n\n\n\n\n\n') print("---- IDDFS -----") node, tree = iddfs(State2((3, 3, 1), (3, 3, 1), "Start")) if node is not None: print("- Tree -")
from greedy import * from astar import * from ac3 import * from backtracking import * from sudoku import * if __name__ == '__main__': # Lendo argumentos: filename = sys.argv[1] algorithm = sys.argv[2] if algorithm == "bfs": for board in read_board(filename): print(bfs(board)) elif algorithm == "dfs": for board in read_board(filename): print(dfs(board)) elif algorithm == "greedy": for board in read_board(filename): print(greedy(board, h1)) elif algorithm == "astar": for board in read_board(filename): print(astar(board, g, h1)) elif algorithm == "ac3": for board in read_board(filename): csp = CSP(board) print(AC3(csp, csp.queue())) elif algorithm == "backtracking": for board in read_board(filename): print(backtracking(CSP(board)))
if thank_you_auto_move: auto_move((x[p] - 1, y[p]), p) if keys[pygame.K_w] and a[x[p] - 1][y[p]] != 1: draw_player(-1, 0, p) x[p] -= 1 if thank_you_auto_move: auto_move((x[p] + 1, y[p]), p) # Условие прохождения лабиринта for i in range(players): if x[i] == n + 3 and y[i] == m + 1: in_game = False if restart_dfs or restart_prim or restart_kruskal: new_maze() if restart_dfs: dfs() elif restart_prim: prim() else: if vt_index == -1: vt = visual_types[vt_count] vt_count = (vt_count + 1) % len(visual_types) else: vt = visual_types[vt_index] kruskal(vt) # Выход a[n + 2][m + 1] = a[n + 3][m + 1] = 0 # Максимальный путь max_i, max_j = max_cell(bfs())
def test_path_found1(self): path = ['s', 'e', 'r', 'f', 'g'] self.assertEqual(dfs('s', 'g', self.g1), path)
for row in con: i = row[0] j = row[1] d = row[2] distance_matrix[i][j] = d distance_matrix[j][i] = d #get a adjacency list networklist = [[] for i in range(n)] for row in con: i = row[0] j = row[1] d = row[2] networklist[i].append(j) networklist[j].append(i) bfs_test = bfs(networklist,2) dfs_test = dfs(networklist,2) print('Verticed for bfs: ',bfs_test) print('Vertices for dfs: ',dfs_test) #Results: #Verticed for bfs: [2, 1, 5, 3, 0, 4, 7, 6] #Vertices for dfs: [2, 3, 7, 6, 4, 0, 5, 1]
from dice import state, goal from dfs import * from timeit import Timer initial = state(None, [], 0) print(f"Initial state: {initial}") f = lambda: dfs(initial, goal, 10) res = f() print('has decision :', res[0]) print('open states :', res[2]) print('closed states :', res[3]) print('result path :') for m in res[1]: print(m) t = Timer(f) print("Time = ", t.timeit(number=1))
if __name__ == '__main__': m = Maze(20, 10) print(m) #MazeNode.quiet_mode = False nodes = m.get_node_list() g = Graph() for i in nodes: # add each maze nodes edges to graph if i.u: g.add_edge(i.u, i.u.d) if i.d: g.add_edge(i.d, i.d.u) if i.l: g.add_edge(i.l, i.l.r) if i.r: g.add_edge(i.r, i.r.l) pprint(g) source_node = m.get(0, 0) dfs_result = dfs(g) pprint(dfs_result) print(m) pprint(dfs_result.components) # pprint(topological_sort(g)) - meaning less w/ maze - not acyclic # use otehr data
# Code from this exercise all made by @skdGT print("---- BFS -----") node, tree = bfs(State1((0, 0), (0, 0), "Start"), goal=2) print("- Tree -") tree.print_tree() if node is not None: path = find_path(node) print("- Solution -") print_path(path) else: print("- No Solution -") print('\n\n\n\n\n\n') print("---- DFS -----") node, tree = dfs(State1((0, 0), (0, 0), "Start"), max_depth=10) print("- Tree -") tree.print_tree() if node is not None: path = find_path(node) print("- Solution -") print_path(path) else: print("- No Solution -") print('\n\n\n\n\n\n') print("---- IDDFS -----") node, tree = iddfs(State1((0, 0), (0, 0), "Start")) if node is not None: print("- Tree -") tree.print_tree()
def test_path_infinite_loop(self): path = ['s', 'd', 'e', 'g'] self.assertEqual(dfs('s', 'g', self.g2), path)
def test_path_found2(self): path = ['s', 'e', 'h', 'q'] self.assertEqual(dfs('s', 'q', self.g1), path)
from sys import argv #import all the objects in initGraph, not just import initGraph from initGraph import * #from bfs import * from bfs import * from dfs import * from astar import * from datetime import datetime startTime = datetime.now() # the arguments from user inputs. script, city1, city2, routingopt, algoopt= argv #print G.node[city1] #print G.node[city2] # 'is' is to test if the two object is exactly the same, # while == is for the testing of the value of stings themselves. if algoopt == 'bfs': bfs(city1,city2,routingopt) elif algoopt == 'dfs': dfs(city1,city2,routingopt) elif algoopt == 'astar': astar(city1,city2,routingopt) else: print 'Only bfs, dfs, and astar are supported!' #print algoopt print 'Run time: %s'%(str(datetime.now() - startTime)) print '=================================================================='
return locations def mark(self, path): for maze_location in path: self._grid[maze_location.row][maze_location.col] = Cell.PATH self._grid[self.start.row][self.start.col] = Cell.START self._grid[self.goal.row][self.goal.col] = Cell.GOAL def clear(self, path): for maze_location in path: self._grid[maze_location.row][maze_location.col] = Cell.EMPTY self._grid[self.start.row][self.start.col] = Cell.START self._grid[self.goal.row][self.goal.col] = Cell.GOAL if __name__ == '__main__': m = Maze() print(m) solution1 = dfs(m.start, m.goal_test, m.successors) if solution1 is None: print("No solution for dfs") else: path1 = node_to_path(solution1) m.mark(path1) print(m) m.clear(path1)
# BFS s = 8 edges = [(0, 1, None), (0, 2, None), (2, 3, None), (3, 4, None), (3, 5, None), (4, 5, None), (4, 6, None), (5, 7, None), (6, 7, None)] g = Graph(0, s, edges) assert(bfs(g, 0) == [0, 1, 2, 3, 4, 5, 6 ,7]) # DFS assert(dfs(g, 0) == [0, 1, 2, 3, 4, 5, 7, 6]) # Topological Sort s = 9 edges = [(0, 1, None), (0, 4, None), (1, 2, None), (1, 4, None), (2, 7, None), (3, 4, None), (5, 2, None), (5, 6, None), (6, 7, None)] dag0 = Graph(1, s, edges) assert(check_top_sort(dag0, top_sort(dag0)))
def test_path_target_not_found1(self): path = [] self.assertEqual(dfs('s', 'z', self.g1), None)
from sudoku import state_sudoku from dfs import * from timeit import Timer initial = state_sudoku() def goal(state): for row in state.table: for col in row: if col == 0: return False return True print(f"Initial state: {initial}") f = lambda: dfs(initial, goal, 20) res = f() print('has decision :', res[0]) print('open states :', res[2]) print('closed states :', res[3]) print('result path :') for m in res[1]: print(m.show()) t = Timer(f) print("Time = ", t.timeit(number=1))
def topological_sort(g): dfs_result = dfs(g) dfs_result.order.reverse() return dfs_result.order