def test_queue(): q = Queue() q.enqueue(3) assert_equal(1, q.size()) assert_equal(3, q.dequeue()) q.enqueue(2) q.enqueue(1) assert_equal([2, 1], list(q)) assert_equal(2, q.dequeue())
def bfs(graph, starting_vertex, destination_vertex): """ Return a list containing the shortest path from starting_vertex to destination_vertex in breath-first order. """ # Create a q and enqueue starting vertex qq = Queue() qq.enqueue([starting_vertex]) # Create a set of traversed vertices visited = set() # visited = [] # While queue is not empty: while qq.size() > 0: # dequeue/pop the first vertex path = qq.dequeue() # if not visited if path[-1] not in visited: # DO THE THING!!!!!!! print(path[-1]) # mark as visited visited.add(path[-1]) print(path) # visited.append(path[-1]) # enqueue all neightbors if path[-1] == destination_vertex: return path for next_vert in graph[path[-1]].keys(): new_path = list(path) # print(new_path) new_path.append(next_vert) qq.enqueue(new_path) # print(visited) pass # TODO
def bfs(visited_rooms): visited = set() my_queue = Queue() room = player.current_room # add room id my_queue.enqueue([room.id]) while my_queue.size() > 0: path = my_queue.dequeue() # the last node end = path[-1] if end not in visited: visited.add(end) # checks if last room has been visited for exit_direction in visited_rooms[end]: # if no exit exists if (visited_rooms[end][exit_direction] == '?'): return path # if not visited elif (visited_rooms[end][exit_direction] not in visited): # create/ add a new path new_path = path + [visited_rooms[end][exit_direction]] # add the new path my_queue.enqueue(new_path) return path
def __bfs(graph, beg_id, end_id, shortest_path=True): first = graph.vtx_map[beg_id] queue = Queue([first]) visited = set([first.id]) nearest_prevs_hmap = {} found = False while len(queue) != 0: # explore: (prev node not always unique.) # Goes through all nodes prev_node = queue.dequeue() neighbors_ids_wts = prev_node.adj_list for cur_id, _ in neighbors_ids_wts: if cur_id not in visited: # visit: (cur_node always unique) # update `queue` and `visited` queue.enqueue(graph.vtx_map[cur_id]) visited.add(cur_id) # action - populate hmap # can break if end_id is found cz # we add all nearest prevs until `cur_id` in lookup table nearest_prevs_hmap[cur_id] = prev_node.id if cur_id == end_id: found = True break if found is True: break # at end of bfs traversal/search return nearest_prevs_hmap
def bfs(self, starting_vertex, destination_vertex): """ Return a list containing the shortest path from starting_vertex to destination_vertex in breath-first order. """ # make a queue queue = Queue() # make a visited set visited = set() # enqueue the PATH to that node queue.enqueue([starting_vertex]) # While queue isn't empty while queue.size(): # dequeue the PATH path = queue.dequeue() # the last thing in the path is our current item node = path[-1] # if node is not visited: if node not in visited: # CHECK if it's the target if node == destination_vertex: # if so, return the path return path visited.add(node) # for each of the node's neighbor's for neighbor in self.vertices[node]: #copy the path PATH_COPY = path.copy() # add neighbor to the path PATH_COPY.append(neighbor) # enqueue the PATH_COPY queue.enqueue(PATH_COPY) return None
def bft(self, starting_vertex: T) -> None: """ Print each vertex in breadth-first order beginning from starting_vertex. """ # keep track of visited vertices visited = set() # create a queue class queue = Queue() # enqueue the starting vertex queue.enqueue(starting_vertex) # while queue is not empty while queue.size(): # dequeue the queue current_vertex = queue.dequeue() # if current vertex has not been visited if current_vertex not in visited: # add ti to visited visited.add(current_vertex) # print the current vertex print(current_vertex) # for every neighbors of current_vertex for vertex in self.vertices[current_vertex]: # add it to the queue queue.enqueue(vertex)
def BFS(self, s): ''' Breadth first search algorithm (BFS) Input: s - start vertex Output: visited (set) - the set of accessible vertices from s prev (dictionary) - each key has as value the vertex that is previous to the key in the BFS path dist (dictionary) - each key represent a vertex and has as value the length of the shortest path from s to it ''' visited = set() # set q = Queue() # queue prev = {} # dictionary dist = {} # dictionary prev[s] = None dist[s] = 0 q.enqueue(s) while len(q) > 0: x = q.dequeue() # get the next element from the queue for y in self.__dg.iterateOut(x): if y not in visited: visited.add(y) q.enqueue(y) prev[y] = x dist[y] = dist[x] + 1 return visited, prev, dist
def find_room(self): # implement bfs to find path to nearest unseen room # def bfs(self, starting_vertex, destination_vertex): # """ # Return a list containing the shortest path from # starting_vertex to destination_vertex in # breath-first order. # """ # initialize queue with starting vertex queue = Queue() queue.enqueue((self.current_room, [])) # set to keep track of vertexes already seen visited = set() # while queue is not empty while queue.size() > 0: # get path and vertex room, path = queue.dequeue() # if room has not been seen, return path if room.id not in self.seen: return path # else, add vertex to visited elif room.id not in visited: visited.add(room.id) # and add paths to the queue for each edge for exit in room.get_exits(): path_copy = path.copy() path_copy.append(exit) queue.enqueue((room.get_room_in_direction(exit), path_copy)) print('Room not found')
def find_shortest_path(graph, starting_room): qq = Queue() visited = set() qq.enqueue([starting_room]) while qq.size() > 0: path = qq.dequeue() move = path[-1] room = path[-1].origin if move.dir: room = graph[room][move.dir] if room not in visited: visited.add(room) for exit in graph[room]: # Target(?) found! if graph[room][exit] == '?': new_move = Move(room, exit) return path[1:], new_move # If target not found make a new move and append to queue elif exit != '?' and graph[room][exit] not in visited: new_path = list(path) new_move = Move(room, exit) new_path.append(new_move) qq.enqueue(new_path) return None, None
def get_directions(starting_room, destination_room, all_rooms): # Create an empty queue queue = Queue() # Add a path for starting_room_id to the queue # Add a second option that recalls to room zero first # paths will contain tuple of (direction, room_id) queue.enqueue([(None, starting_room)]) # queue.enqueue([(None, starting_room), (None, 0)]) # Create an empty set to store visited rooms visited = set() while queue.size() > 0: # Dequeue the first path path = queue.dequeue() # Grab the last room from the path room = path[-1][1] # If room is the desination, return the path if room == destination_room: return path[1:] # If it has not been visited... if room not in visited: # Mark it as visited visited.add(room) # Then add a path all neighbors to the back of the queue current_room = all_rooms[str(room)] adjacent_rooms = [] for e in current_room['exits']: adjacent_rooms.append((e, current_room['exits'][e])) for next_room in adjacent_rooms: queue.enqueue(path + [next_room])
def bfs(start_room, map): # Create an empty Queue and enqueue path to starting_vertex q = Queue() q.enqueue([start_room]) # Create empty set to store visted nodes visited = set() # While queue is not empty: while q.size() > 0: # Dequeue the first path path = q.dequeue() # get vertex from end of path node = path[-1] # if the vertex has not been visited if node not in visited: # mark it visted visited.add(node) # Check if it contains a "?" if "?" in map[node].values(): return path # then add a path to all adjacent vertices to back of queue for neighbor in map[node].values(): # copy path copy_path = path.copy() # append next vert to back of copy copy_path.append(neighbor) # enqueue copy q.enqueue(copy_path) return None
def linearize_level_ordered(self, level=1): graph_str = '' bfs_queue = Queue() cur_level_count = 0 visited = {key: False for key in self.graph} for root in self.roots: bfs_queue.enqueue(root) cur_level_count += 1 while not bfs_queue.isEmpty() and level > 0: next_level_count = 0 while cur_level_count > 0: cur_item = bfs_queue.dequeue() if not visited[cur_item]: visited[cur_item] = True if global_info.node_labels[cur_item].find( 'name_' ) != -1 or global_info.node_labels[cur_item].find( 'date-entity' ) != -1: # skip name and date entity as global concepts cur_level_count -= 1 continue graph_str += global_info.node_labels[cur_item] + _SPACE for neighbour in self.graph[cur_item].adjacency_list: next_level_count += 1 bfs_queue.enqueue(neighbour[0]) cur_level_count -= 1 cur_level_count = next_level_count level -= 1 return graph_str
def bfs(self, starting_vertex, destination_vertex): """ Return a list containing the shortest path from starting_vertex to destination_vertex in breath-first order. """ # make a queye q = Queue() # make a set to track the nodes visited = set() path = [starting_vertex] # enqueue the starting node q.enqueue(path) # while the queue isn't empty while q.size() > 0: ## dequee the node at the front of the line current_path = q.dequeue() current_node = current_path[-1] ### if this node is out targte node if current_node == destination_vertex: #### return it!! return True return current_path ### if not visted if current_node not in visited: #### mark as visited visited.add(current_node) #### get neigghbots neighbors = self.vertices[current_node].keys() # for each neibor for neighbor in neighbors: path = list(current_node) # add to queue path.append(neighbor) q.enqueue(path)
def solve(board, robots, dest, dest_color, num_sols=3, max_depth=20): """ Robots denotes the position and orientation (above or below a diag) of the robots. The robot of color DEST_COLOR must get to the square given by DEST (an (x, y) tuple). A list of Solution objects are returned, NUM_SOLS many of them (the best, second best, etc.) If we haven't found a solution less than MAX_DEPTH, give up """ assert len(robots) == 4, "there must be 4 robots" assert dest_color in ["yellow", "red", "green", "blue"] assert num_sols >= 0 and max_depth >= 0, "Cannot have a negative number of solutions or max depth" print "Trying to move", dest_color, "robot to", dest solutions = [] if num_sols == 0: return solutions # initialize the BFS fringe initial_sol = Solution(robots) bfs_fringe = Queue() bfs_fringe.enqueue(initial_sol) # in loop: dequeue, check if solution, add all next positions to queue curr_depth = 0 num_sols_at_depth = 0 while True: assert not bfs_fringe.empty(), "BFS fringe is empty" # dequeue the Solution at the front of the stack curr_sol = bfs_fringe.dequeue() # if it is a valid solution for the board, add it to the list of solutions to return if board.isSolution(curr_sol, dest, dest_color): solutions.append(curr_sol) if len(solutions) == num_sols: return solutions if curr_sol.depth > curr_depth: print "Examined", num_sols_at_depth, "solutions at depth", curr_depth curr_depth = curr_sol.depth num_sols_at_depth = 0 # check that the depth of this solution does not exceed max depth num_sols_at_depth += 1 if num_sols_at_depth % 100 == 0: print "Examined", num_sols_at_depth, "solutions at depth", curr_depth if curr_sol.depth > max_depth: break # for each of the possible robot moves, make the move, grab the new Solution and enqueue it next_moves = board.allNextMoves(curr_sol) for next_move in next_moves: bfs_fringe.enqueue(next_move) return solutions
def build_path(self, G, s): self.marked[s] = True queue = Queue() queue.enqueue(s) while not queue.is_empty(): v = queue.dequeue() for w in G.adj[v]: if not self.marked[w]: self.edge_to[w] = v self.marked[w] = True queue.enqueue(w)
def playing(player): traversal_path = [] visited_dict = {} visited_set = set() path = Stack() oposite_directions = {"s": "n", "n": "s", "e": "w", "w": "e"} while len(visited_set) < len(room_graph): current = player.current_room visited_set.add(current) # path.push(current.id) # traversal_path.append(current) # if current.id not in visited_set: # print(current.id) # visited_set.add(current.id) visited_dict[current.id] = {} # if len(current.get_exits()) == 1: # direction = current.get_exits() # path.pop() # previous_room = path.stack[-1] # visited_dict[current.id][direction] = previous_room # player.travel(previous_room) unvisited = Queue() for direction in current.get_exits(): if current.get_room_in_direction(direction) not in visited_set: # visited_dict[current.id][direction] = False # unvisited.enqueue(direction) unvisited.enqueue(direction) if unvisited.size() > 0: # direction = unvisited.dequeue() direction = unvisited.dequeue() path.push(direction) traversal_path.append(direction) player.travel(direction) else: # for direction in visited_dict[current.id]: # if visited_dict[current.id][direction] == False: # visited_dict[current.id][direction] = player.current_room.get_room_in_direction(direction) # player.travel(direction) previous_room = path.pop() traversal_path.append(oposite_directions[previous_room]) player.travel(oposite_directions[previous_room]) return traversal_path
def traverse(start, target, db): que = Queue() # enqueue first room que.enqueue({"node": start, "path": []}) visited = set() print(f'Traversing back from {start["room_id"]} to {target["room_id"]}') while que.size() > 0: current_room = que.queue[0] cr_id = current_room["node"]["room_id"] if cr_id not in visited: visited.add(cr_id) if cr_id == target["room_id"]: current_room["path"].append(cr_id) print(f"Returning on this path: {current_room['path']}") print(f"Estimated travel time: {(len(current_room['path'])*16)//60} minutes") return current_room["path"] db_id = db.get_id() game_map = db.get_map(db_id) # add all neighbouring nodes to queue for direction in current_room["node"]["exits"]: # get ID of the room, that is in direction if direction in game_map[str(cr_id)]: room_in_direction_id = game_map[str(cr_id)][direction] # grab that room from DB room = db.get_room_by_id(room_in_direction_id) # Make a COPY of the PATH set from current node to neighbour nodes path_to_neighbour = current_room["path"].copy() path_to_neighbour.append(cr_id) que.enqueue( {"node": room, "path": path_to_neighbour}) else: print(f"Missing direction in map") print(f"Room: {cr_id} in dir '{direction}'. Map for room: {game_map[str(cr_id)]}") que.dequeue() return None
def find_unexplored_room(): q = Queue() for d in player.current_room.get_exits(): q.enqueue([(player.current_room, d)]) visited = set() while q.size: path = q.dequeue() curr_room = path[-1][0] if "?" in gr.rooms[curr_room].values(): return [d for _, d in path][1:] elif curr_room not in visited: visited.add(curr_room) for direction in curr_room.get_exits(): next_room = curr_room.get_room_in_direction(direction) q.enqueue(path + [(next_room, direction)]) return None
def AC3(csp): """ Returns False if an inconsistency is found, True otherwise Input: A CSP with components (X, D, C) """ # Initially, the queue has all the arcs in the CSP queue = Queue(csp.arcs()) while not queue.isEmpty(): (Xi, Xj) = queue.dequeue() if revise(csp, Xi, Xj): if len(csp.domain(Xi)) == 0: return False for Xk in csp.neighbors(Xi, Xj): queue.enqueue((Xk, Xi)) return True
def get_all_social_paths(self, user_id): """ Takes a user's user_id as an argument Returns a dictionary containing every user in that user's extended network with the shortest friendship path between them. The key is the friend's ID and the value is the path. """ # visited = {} # Note that this is a dictionary, not a set # # !!!! IMPLEMENT ME # q = Queue() # # enqueue the first user # q.enqueue([user_id]) # # while the queue has something in it # while q.size() > 0: # # create a path starting with the first thing in the queue # path = q.dequeue() # user = path[-1] # if user not in visited: # visited[user] = path # for next_user in self.friendships[user]: # new_path = list(path) # new_path.append(next_user) # q.enqueue(new_path) # return visited '''This is the code BEEJ made in class''' q = Queue() # visited = set() # result = {} visited = {} q.enqueue([user_id]) # make this a list while q.size() > 0: path = q.dequeue() u = path[-1] if u not in visited: # visited.add(u) # result[u] = path visited[u] = path for neighbor in self.friendships[u]: path_copy = list(path) path_copy.append(neighbor) q.enqueue(path_copy) # return result return visited
def uncharted_path(currentPath, room_id, player): # Create an empty set to store visited nodes visited = set() # Create an empty Queue and enqueue A PATH TO the starting vertex q = Queue() path = [room_id] q.enqueue(path) # While the queue is not empty... while q.size() > 0: # Dequeue the first PATH p = q.dequeue() # GRAB THE VERTEX FROM THE START OF THE PATH v = p[0] # IF VERTEX == TARGET ('?'), SET PATH THEN BREAK if v == '?': path = p[1:] break # If that vertex has not been visited... if v not in visited: # Mark it as visited visited.add(v) # Then add A PATH TO all of its neighbors to the back of the queue for neighbors in currentPath[v]: node = currentPath[v][neighbors] new_path = p.copy() new_path.insert(0, node) q.enqueue(new_path) # this list will contain the directions that the player needs to move back movements = [] # While loop runs trying to create a path of movements while len(path) > 1: # remove the last room and store as a variable current = path.pop(-1) # find the direction that will take you to the prior room and add it to a movements list for route in currentPath[current]: if currentPath[current][route] == path[-1]: movements.append(route) # for every element in movements, move in that direction until you reach the spot for move in movements: player.travel(move) # return the movements to be appended to traversalPath return movements
def bft(room_data, room_conns): cue = Queue() cue.enqueue([str(room_data[-1]["room_id"])]) visited = set() while cue.size() > 0: room_list = cue.dequeue() room = room_list[-1] if room not in visited: visited.add(room) for direction in room_conns[room]: if room_conns[room][direction] == "?": return room_list else: path = list(room_list) path.append(room_conns[room][direction]) cue.enqueue(path) return None
def findUnexploredRoom(): current_room = readCurrentRoom() q = Queue() q.enqueue([current_room['room_id']]) while q.size(): path = q.dequeue() room = path[-1] for i in traversalGraph[room]: if traversalGraph[room][i] == "?": return path else: path_copy = path[:] path_copy.append(traversalGraph[room][i]) q.enqueue(path_copy) return None
def traverse(self, room_conns, room_data, room_id, end_room): cue = Queue() checked = set() paths = {} cue.enqueue(room_id) paths[room_id] = [room_id] while cue.size() > 0: current = cue.dequeue() checked.add(current) for possibles in room_conns[str(current)].values(): if possibles in checked or possibles == "?": continue new = paths[current][:] new.append(possibles) paths[possibles] = new found = False for data in room_data: if possibles == str(data['room_id']): if data['title'].lower() == end_room.lower(): found = True break if 'items' in data and 'small treasure' in data[ 'items']: found = True break elif 'items' in data and 'tiny treasure' in data[ 'items']: found = True break if possibles == end_room: found = True if found: the_path = paths[possibles] exits = [] for step in range(len(the_path) - 1): exits.append( self.compass(room_conns, str(the_path[step]), the_path[step + 1])) return exits cue.enqueue(possibles) return None
def bfs(current_room, end_room): """ Return a list containing the shortest path from starting_vertex to destination_vertex in breath-first order. """ q = Queue() q.enqueue([current_room]) visited = set() while q.size() > 0: path = q.dequeue() v = path[-1] if v not in visited: if v == end_room: return path visited.add(v) for key, value in room_conn[str(v)].items(): new_path = list(path) new_path.append(value) q.enqueue(new_path) return None
def linearize_level_ordered(self, level = 1): graph_str = '' bfs_queue = Queue() cur_level_count = 0 visited = {key:False for key in self.graph} for root in self.roots: bfs_queue.enqueue(root) cur_level_count += 1 while not bfs_queue.isEmpty() and level > 0: next_level_count = 0 while cur_level_count > 0: cur_item = bfs_queue.dequeue() if not visited[cur_item]: visited[cur_item] = True if global_info.node_labels[cur_item].find('name_') != -1 or global_info.node_labels[cur_item].find('date-entity') != -1: # skip name and date entity as global concepts cur_level_count -= 1 continue graph_str += global_info.node_labels[cur_item] + _SPACE attribute_dict = global_info.get_attribute_dict() for neighbour in self.graph[cur_item].adjacency_list: next_level_count += 1 bfs_queue.enqueue(neighbour[0]) attribute_dict[neighbour[1]] = global_info.node_labels[neighbour[0]] for k in sorted(attribute_dict): graph_str += k + _SPACE if k == 'time': graph_str += (attribute_dict[k] if attribute_dict[k] == _EMPTY else attribute_dict[k][12:]) + _SPACE else: graph_str += attribute_dict[k] + _SPACE cur_level_count -= 1 cur_level_count = next_level_count level -= 1 return graph_str
def bfs(self, starting_vertex: T, destination_vertex: T) -> PathType: """ Return a list containing the shortest path from starting_vertex to destination_vertex in breath-first order. """ # create the queue class queue = Queue() # would hold the visited vertices visited = set() # add the starting vertex as a list of vert queue.enqueue([starting_vertex]) # while the queue is not empty while queue.size(): # dequeue a path from the queue path = queue.dequeue() # get the last vertex from the path current_vert = path[-1] # if the current_vert is teh destination vert if current_vert == destination_vertex: # return the path return path # if current_vert has not been visited if current_vert not in visited: # add it to visited visited.add(current_vert) # for every neighbors of current_vert for vertex in self.vertices[current_vert]: # create a copy of the path new_path = list(path) # add the current vertex to the new path new_path.append(vertex) # enqueue the new_path onto the queue queue.enqueue(new_path)
def get_all_social_paths(self, user_id): """ Takes a user's user_id as an argument Returns a dictionary containing every user in that user's extended network with the shortest friendship path between them. The key is the friend's ID and the value is the path. """ visited = {} # Note that this is a dictionary, not a set # !!!! IMPLEMENT ME q = Queue() q.enqueue([user_id]) while q.size() > 0: path = q.dequeue() user = path[-1] if user not in visited: visited[user] = path for next_user in self.friendships[user]: new_path = list(path) new_path.append(next_user) q.enqueue(new_path) return visited
def bfs_to_unexplored(self, starting_room_id): """Find path to shortest unexplored room using breadth-first search""" queue = Queue() # paths will contain tuple of (direction, room_id) queue.enqueue([(None, starting_room_id)]) visited = set() while queue.size() > 0: current_path = queue.dequeue() current_room_id = current_path[-1][1] current_exits = self.get_exits(current_room_id) if '?' in current_exits.values(): # slice off the current room and return path return current_path[1:] if current_room_id not in visited: visited.add(current_room_id) for direction, room_id in current_exits.items(): path_to_next_room = current_path + [(direction, room_id)] queue.enqueue(path_to_next_room) return None
def bfs(start_room, map): visited = set() q = Queue() q.enqueue([start_room]) while q.size() > 0: # dequeue the path path = q.dequeue() node = path[-1] if node not in visited: visited.add(node) # Check if it contains a "?" if "?" in map[node].values(): return path for neighbor in map[node].values(): # print(f"Neighbor found: {neighbor}") copy_path = path.copy() copy_path.append(neighbor) q.enqueue(copy_path) return None