def dijkstra_shortest_path(self, start, end): pre_grids = PQ() grid_dist = PQ() grid_dist[start] = 0 pre_grids[start] = -1 while grid_dist: cur = grid_dist.smallest() for g in [-81,81,-1,1]: g+=cur if 0>g or g>=len(self.grid): continue if g in pre_grids: continue if self.grid[g] == "grass": continue if self.grid[g] == "soul_sand": if g not in grid_dist or grid_dist[g] > grid_dist[cur]+4: grid_dist[g] = grid_dist[cur]+4 pre_grids[g] = cur elif self.grid[g] == "stone": if g not in grid_dist or grid_dist[g] > grid_dist[cur]+1: grid_dist[g] = grid_dist[cur]+1 pre_grids[g] = cur else: if g not in grid_dist or grid_dist[g] > grid_dist[cur]: grid_dist[g] = grid_dist[cur] pre_grids[g] = cur del grid_dist[cur] result = [] cur = end while pre_grids[cur] != -1: result.insert(0,cur) cur = pre_grids[cur] result.insert(0,start) return result
def dijkstra_shortest_path(grid_obs, source, dest): ## helper functions def extract_min(queue): if len(queue) == 0: return None val = queue.smallest() del queue[val] return val ## Dijkstra's Algorithm dist = [] prev = [] pq = PQ() for i in range(len(grid_obs)): if i == source: dist.append(0) else: dist.append(float('inf')) prev.append(-1) pq[i] = dist[i] while len(pq) > 0: u = extract_min(pq) for v in get_neighbor(u,grid_obs): alt = dist[u] + 1 if alt < dist[v]: dist[v] = alt prev[v] = u pq[v] = alt return prev[dest] if len(prev) > 0 else -1
def dijkstra_shortest_path(grid_obs, source, dest, danger_blocks=[]): """ Finds the shortest path from source to destination on the map. It used the grid observation as the graph. See example on the Tutorial.pdf file for knowing which index should be north, south, west and east. Args grid_obs: <list> list of block types string representing the blocks on the map. source: <int> source block index. dest: <int> destination block index. Returns path_list: <list> block indexes representing a path from source (first element) to destination (last) """ action_trans = {'north': -21, 'south': 21, 'west': -1, 'east': 1} path_set = set() # indexes priority_dict = PQ() # key = index, value = distance value parent = [-1] * len(grid_obs) for i in range(0, len(grid_obs)): if (grid_obs[i] in danger_blocks): continue priority_dict[i] = math.inf priority_dict[source] = 0 while (len(priority_dict) != 0): # picking vertex with minimum distance (smallest() from priority queue) and is not in the path set # priority dict should not contain vertices added to path_list smallest_vertex = priority_dict.smallest() smallest_vertex_distance = priority_dict[smallest_vertex] # adding u to the path set path_set.add(smallest_vertex) # removing from priority dict priority_dict.pop(smallest_vertex) for adj_index in [ smallest_vertex + modifier for modifier in action_trans.values() ]: if adj_index in priority_dict: # sum of distance value u (in priority queue) and edge u-v (always 1) new_distance_value = smallest_vertex_distance + 1 v_distance_value = priority_dict[adj_index] if (new_distance_value < v_distance_value): # update if new distance value is less than value saved in data structure priority_dict[adj_index] = new_distance_value # update parent parent[adj_index] = smallest_vertex # generating shortest path utilizing parents (in reverse order) path_list = [dest] while (True): current_parent = parent[path_list[-1]] if (current_parent == -1): break path_list.append(current_parent) return list(reversed(path_list))
def dijkstra_shortest_path(grid_obs, source, dest): """ Finds the shortest path from source to destination on the map. It used the grid observation as the graph. See example on the Tutorial.pdf file for knowing which index should be north, south, west and east. Args grid_obs: <list> list of block types string representing the blocks on the map. source: <int> source block index. dest: <int> destination block index. Returns path_list: <list> block indexes representing a path from source (first element) to destination (last) """ #------------------------------------ # # Fill and submit this code # predecessors = {source: float('inf')} visited_blocks = {source: 0} queue = PQ() queue.__setitem__(source, 0) goodIndices = [] print len(grid_obs) for index in range(len(grid_obs)): if grid_obs[index] != "air": goodIndices.append(index) for index in goodIndices: if index != source: visited_blocks[index] = float('inf') while queue: blocks_to_go = [] current_position = queue.smallest() del queue[current_position] for difference in [-81, -1, 1, 81]: if (current_position + difference) in goodIndices: blocks_to_go.append(current_position + difference) for block_Index in blocks_to_go: gap = visited_blocks[current_position] + 1 if gap < visited_blocks[block_Index]: visited_blocks[block_Index] = gap predecessors[block_Index] = current_position queue.__setitem__(block_Index, gap) shortest_paths = [] while dest != source: shortest_paths.append(dest) dest = predecessors[dest] shortest_paths.append(source) shortest_paths.reverse() return shortest_paths
def dijkstra_shortest_path(grid_obs, source, dest): """ Finds the shortest path from source to destination on the map. It used the grid observation as the graph. See example on the Tutorial.pdf file for knowing which index should be north, south, west and east. Args grid_obs: <list> list of block types string representing the blocks on the map. source: <int> source block index. dest: <int> destination block index. Returns path_list: <list> block indexes representing a path from source (first element) to destination (last) """ #------------------------------------ path_list, vertices, prev, dist = [], PQ(), dict(), dict() # ========== Initialize vertices, prev, and dist ========== for index in range(len(grid_obs)): # Initialize all blocks' previous ones to None (not decide yet) prev[index] = None # Initialize the priority queue dist[index] = sys.maxint dist[source] = 0 vertices[source] = 0 # ========== Finished the Initialization ========== while vertices: u = vertices.smallest() cur = vertices[u] vertices.pop(u) # Find out the blocks around u from 4 directions north, south, west, east = u - 21, u + 21, u - 1, u + 1 directions = [north, south, west, east] for direction in directions: if (grid_obs[direction] != 'air' and dist[u] != sys.maxint): if (dist[direction] > dist[u] + 1): dist[direction] = dist[u] + 1 prev[direction] = u vertices[direction] = cur + 1 cur_block = prev[dest] while cur_block != source: path_list.append(cur_block) cur_block = prev[cur_block] path_list.append(cur_block) path_list.reverse() path_list.append(dest) return path_list
def dijkstra_shortest_path(self): pre_grids = PQ() grid_dist = PQ() grid_dist[self.start] = 0 pre_grids[self.start] = -1 while grid_dist: cur = grid_dist.smallest() for g in [-self.up_down_dist,self.up_down_dist,-1,1]: g+=cur if g not in pre_grids and self.grid[g] != "air": if g not in grid_dist or grid_dist[g] > grid_dist[cur]+1: grid_dist[g] = grid_dist[cur]+1 pre_grids[g] = cur del grid_dist[cur] result = [] cur = self.end while pre_grids[cur] != -1: result.insert(0,cur) cur = pre_grids[cur] result.insert(0,self.start) return result
def dijkstra(self, start, dest): start_dist = 0 priorityQ = PQ() priorityQ.setdefault(start, start_dist) trace = dict() visited = set() trace[start] = [None, start_dist] while (True): #print("AIHSHDAHDHSIHIDDSDASHDSADSIAHSDAH") current = priorityQ.smallest() #print(current) del priorityQ[current] if (current == dest): break visited.add(current) n, e, s, w = self.getAdjacents(current) if (n[1] < self.northMax and self.wumpusMap[n[0]][n[1]] == 0 and self.pitMap[n[0]][n[1]] == 0 and n not in visited): priorityQ.setdefault(n, trace[current][1] + 1) trace[n] = [current, trace[current][1] + 1] if (s[1] >= 0 and self.wumpusMap[s[0]][s[1]] == 0 and self.pitMap[s[0]][s[1]] == 0 and s not in visited): priorityQ.setdefault(s, trace[current][1] + 1) trace[s] = [current, trace[current][1] + 1] if (e[0] < self.eastMax and self.wumpusMap[e[0]][e[1]] == 0 and self.pitMap[e[0]][e[1]] == 0 and e not in visited): priorityQ.setdefault(e, trace[current][1] + 1) trace[e] = [current, trace[current][1] + 1] if (w[0] >= 0 and self.wumpusMap[w[0]][w[1]] == 0 and self.pitMap[w[0]][w[1]] == 0 and w not in visited): priorityQ.setdefault(w, trace[current][1] + 1) trace[w] = [current, trace[current][1] + 1] path = [dest] last = dest while (True): if (trace[last][0] is None): break path.insert(0, trace[last][0]) last = trace[last][0] return path
def get_shortest_path(self, grid_obs, source, dest): q = PQ() self.init_pq(grid_obs, q) q[source] = 0 prev = dict() dist = q.copy() [prev.update({key: None}) for key in q.keys()] for node in q: neighbors = [] if node not in range(0, 21) and grid_obs[node - 21] in [ 'air', 'wooden_door', 'tallgrass', 'double_plant' ]: neighbors.append(node - 21) if (node + 1) % 21 != 0 and grid_obs[node + 1] in [ 'air', 'wooden_door', 'tallgrass', 'double_plant' ]: neighbors.append(node + 1) if node % 21 != 0 and grid_obs[node - 1] in [ 'air', 'wooden_door', 'tallgrass', 'double_plant' ]: neighbors.append(node - 1) if node not in range(420, 441) and grid_obs[node + 21] in [ 'air', 'wooden_door', 'tallgrass', 'double_plant' ]: neighbors.append(node + 21) for n in neighbors: alt = 0 if n in dist: alt = dist[node] + 1 if alt < dist[n]: dist[n] = alt prev[n] = node q[n] = alt path_list = [dest] last = dest while last != source: path_list = [prev[last]] + path_list last = prev[last] return path_list
def GetMissionXML(seed, gp, size=10): return '''<?xml version="1.0" encoding="UTF-8" standalone="no" ?> <Mission xmlns="http://ProjectMalmo.microsoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <About> <Summary>Hello world!</Summary> </About> <ServerSection> <ServerInitialConditions> <Time> <StartTime>1000</StartTime> <AllowPassageOfTime>false</AllowPassageOfTime> </Time> <Weather>clear</Weather> </ServerInitialConditions> <ServerHandlers> <FlatWorldGenerator generatorString="3;7,44*49,73,35:1,159:4,95:13,35:13,159:11,95:10,159:14,159:6,35:6,95:6;12;"/> <DrawingDecorator> <DrawSphere x="-27" y="70" z="0" radius="30" type="air"/> </DrawingDecorator> <MazeDecorator> <Seed>''' + str(seed) + '''</Seed> <SizeAndPosition width="''' + str( size) + '''" length="''' + str( size) + '''" height="10" xOrigin="-32" yOrigin="69" zOrigin="-5"/> <StartBlock type="emerald_block" fixedToEdge="true"/> <EndBlock type="redstone_block" fixedToEdge="true"/> <PathBlock type="diamond_block"/> <FloorBlock type="air"/> <GapBlock type="air"/> <GapProbability>''' + str(gp) + '''</GapProbability> <AllowDiagonalMovement>false</AllowDiagonalMovement> </MazeDecorator> <ServerQuitFromTimeUp timeLimitMs="100000"/> <ServerQuitWhenAnyAgentFinishes/> </ServerHandlers> </ServerSection> <AgentSection mode="Survival"> <Name>CS175AwesomeMazeBot</Name> <AgentStart> <Placement x="0.5" y="56.0" z="0.5" yaw="0"/> </AgentStart> <AgentHandlers> <DiscreteMovementCommands/> <AgentQuitFromTouchingBlockType> <Block type="redstone_block"/> </AgentQuitFromTouchingBlockType> <ObservationFromGrid> <Grid name="floorAll"> <min x="-10" y="-1" z="-10"/> <max x="10" y="-1" z="10"/> </Grid> </ObservationFromGrid> </AgentHandlers> </AgentSection> </Mission>''' """ Used the agent observation API to get a 21 X 21 grid box around the agent (the agent is in the middle). Args world_state: <object> current agent world state Returns grid: <list> the world grid blocks represented as a list of blocks (see Tutorial.pdf) """ while world_state.is_mission_running: #sys.stdout.write(".") time.sleep(0.1) world_state = agent_host.getWorldState() if len(world_state.errors) > 0: raise AssertionError('Could not load grid.') if world_state.number_of_observations_since_last_state > 0: msg = world_state.observations[-1].text observations = json.loads(msg) grid = observations.get(u'floorAll', 0) break return grid """ Finds the shortest path from source to destination on the map. It used the grid observation as the graph. See example on the Tutorial.pdf file for knowing which index should be north, south, west and east. Args grid_obs: <list> list of block types string representing the blocks on the map. source: <int> source block index. dest: <int> destination block index. Returns path_list: <list> block indexes representing a path from source (first element) to destination (last) """ action_trans = {'north': -21, 'south': 21, 'west': -1, 'east': 1} path_set = set() # indexes priority_dict = PQ() # key = index, value = distance value parent = [-1] * len(grid_obs) for i in range(0, len(grid_obs)): if (grid_obs[i] in danger_blocks): continue priority_dict[i] = math.inf priority_dict[source] = 0 while (len(priority_dict) != 0): # picking vertex with minimum distance (smallest() from priority queue) and is not in the path set # priority dict should not contain vertices added to path_list smallest_vertex = priority_dict.smallest() smallest_vertex_distance = priority_dict[smallest_vertex] # adding u to the path set path_set.add(smallest_vertex) # removing from priority dict priority_dict.pop(smallest_vertex) for adj_index in [ smallest_vertex + modifier for modifier in action_trans.values() ]: if adj_index in priority_dict: # sum of distance value u (in priority queue) and edge u-v (always 1) new_distance_value = smallest_vertex_distance + 1 v_distance_value = priority_dict[adj_index] if (new_distance_value < v_distance_value): # update if new distance value is less than value saved in data structure priority_dict[adj_index] = new_distance_value # update parent parent[adj_index] = smallest_vertex # generating shortest path utilizing parents (in reverse order) path_list = [dest] while (True): current_parent = parent[path_list[-1]] if (current_parent == -1): break path_list.append(current_parent) return list(reversed(path_list))
def dijkstra_shortest_path(grid_obs, source, dest): ## helper functions def extract_min(queue): if len(queue) == 0: return None val = queue.smallest() del queue[val] return val def get_neighbor(u, grid): R_list = [i * 17 for i in range(1, 16)] L_list = [i * 17 - 1 for i in range(2, 17)] candidate = [] ret = [] if u == 0: candidate = [1, 17] elif u == 16: candidate = [15, 33] elif u == 272: candidate = [273, 255] elif u == 288: candidate = [271, 287] elif u in R_list: candidate = [u - 17, u + 1, u + 17] elif u in L_list: candidate = [u - 17, u - 1, u + 17] elif u in range(1, 16): candidate = [u - 1, u + 1, u + 17] elif u in range(273, 288): candidate = [u - 17, u - 1, u + 1] else: candidate = [u - 17, u - 1, u + 1, u + 17] for x in candidate: if grid[x] == u'coal_block': ret.append(x) return ret ## Dijkstra's Algorithm dist = [] prev = [] pq = PQ() for i in range(len(grid_obs)): if i == source: dist.append(0) else: dist.append(float('inf')) prev.append(-1) pq[i] = dist[i] while len(pq) > 0: u = extract_min(pq) for v in get_neighbor(u, grid_obs): alt = dist[u] + 1 if alt < dist[v]: dist[v] = alt prev[v] = u pq[v] = alt return prev[dest] if len(prev) > 0 else -1