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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 bft(self, starting_vertex): """ Print each vertex in breadth-first order beginning from starting_vertex. """ # make a queue queue = Queue() # make a visited set visited = set() # put Starting Vertex in the queue queue.enqueue(starting_vertex) # While queue isn't empty while queue.size(): # dequeue the item, it is our current item node = queue.dequeue() # print(node) # mark Current as Visited visited.add(node) # for all dequeued item's edges for edge in self.vertices[node]: # if not visited if edge not in visited: # put them in queue queue.enqueue(edge)
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. """ # start a Queue for a breadthfirst approach to check all connections qq = Queue() visited = {} # a dictionary not a set # empty list with our user as the starting point path = [user_id] # load the path to back of the Queue qq.enqueue(path) while qq.size() > 0: # set the path removed from the FRONT of the Queue as the path path = qq.dequeue() # set last item in the path which is a list as cur_id cur_id = path[-1] if cur_id not in visited: # set frienships as the value at friendships indexed at cur_id friendships = self.friendships[cur_id] visited[cur_id] = path for friend_id in friendships: new_path = list(path) #copy of path new_path.append(friend_id) # add to back of queue and continues the while loop qq.enqueue(new_path) return visited
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
return None initialize_room() with open("room_data.txt", "r") as rdat: room_data = json.loads(rdat.read()) with open("room_conns.txt", "r") as rconn: room_conns = json.loads(rconn.read()) q2 = Queue() explore(q2) while q2.size() > 0: # Room information with open("room_data.txt", "r") as rdat: room_data = json.loads(rdat.read()) # Room connections with open("room_conns.txt", "r") as rconn: room_conns = json.loads(rconn.read()) player_room = str(room_data[-1]["room_id"]) direction = q2.dequeue() res = requests.post( "https://lambda-treasure-hunt.herokuapp.com/api/adv/move/", json={"direction": direction}, headers={'Authorization': api_key}) data = res.json() room_data.append(data)
def bfs(graph, current_room): """ Return a list containing the shortest path from starting_vertex to destination_vertex in breath-first order. """ # create an empty queue and enqueue A-PATH-TO the starting vertex ID # create a Set to store the visited vertices # while the queue is not empty .. # dequeue the first PATH # grab the last vertex from the PATH # if that vertex has not been visited .. # check if its the target #if yes, return path #mark it as visited # add A PATH TO its neighbots to the back of the queue # copt the path # append the neighbor to the back dirs = ["n", "s", "e", "w"] # create an empty Queue queue = Queue() #push the starting vertex ID as list queue.enqueue([current_room]) # create an empty Set to store the visited vertices visited = set() # while the queue is not empty ... while queue.size() > 0: # dequeue the first vertex path = queue.dequeue() vert = path[-1] # if that vertex has not been visited .. if vert not in visited: #check for target if "?" in graph.vertices[vert].values(): path_dirs = [] cur_idx = 0 next_idx = 1 last_room = path[-1] print(path) for room in path: if room == last_room: break cur_room = path[cur_idx] next_room = path[next_idx] room_dirs = list(graph.vertices[cur_room].keys()) for d in room_dirs: if graph.vertices[cur_room][d] == next_room: path_dirs.append(d) cur_idx += 1 next_idx += 1 break return path_dirs # mark it is visited visited.add(vert) # then add all of its neighbors to the back of the queue for neighbor in graph.vertices[vert].values( ): #self.get_neighbors(vert) if neighbor not in path: #copy path to avoid pass by reference new_path = list(path) # make a copy new_path.append(neighbor) queue.enqueue(new_path)
def earliest_ancestor(ancestors, starting_node): """ 10 / 1 2 4 11 \ / / \ / 3 5 8 \ / \ \ 6 7 9 Write a function that, given the dataset and the ID of an individual in the dataset, returns their earliest known ancestor – the one at the farthest distance from the input individual. If there is more than one ancestor tied for "earliest", return the one with the lowest numeric ID. If the input individual has no parents, the function should return -1. """ # UPER # use bft # use len(longest) # if len(longest) == 1 then return -1 # check the length of the set of vertices for the longest # if there is no child return -1 # while there is an edge: # ancestor[0] is parent ancestor[1] is child # starting node has no parent then return -1 # initialize with the starting node is equal to the child # after that the child becomes the parent # graph = Graph() # # relatives is a node # for relatives in ancestors: # for relative in relatives: # graph.add_vertex(relative) # # print('GRAPHXXXXXX',graph.vertices) # for relatives in ancestors: # graph.add_edge(relatives[1],relatives[0]) # print('GRAPHXXXXXX',graph.vertices) graph = Graph() for pair in ancestors: graph.add_vertex(pair[0]) graph.add_vertex(pair[1]) graph.add_edge(pair[1], pair[0]) print('XXXXXVERTICESXXXX', graph.vertices) q = Queue() q.enqueue([starting_node]) max_path_len = 1 earliest_ancestor = -1 while q.size() > 0: path = q.dequeue() v = path[-1] # if path is longer or equal and value is smaller, or path is longer if (len(path) >= max_path_len and v < earliest_ancestor) or (len(path) > max_path_len): earliest_ancestor = v max_path_len = len(path) for neighbor in graph.vertices[v]: path_copy = list(path) path_copy.append(neighbor) q.enqueue(path_copy) return earliest_ancestor