Ejemplo n.º 1
0
def bfs(maze, start, end):
    visited = set()

    # Create start and end node
    start_node = Node(None, start)
    start_node.g = 0
    end_node = Node(None, end)
    end_node.g = 0

    queue = []
    queue.append(start_node)

    visited.add(start_node)

    while len(queue) > 0:

        current_node = queue[0]
        queue.pop(0)

        #If end
        if current_node.position == end:
            return get_path(current_node)

        #Create children node
        children = create_child_node(maze, current_node)

        for child in children:

            #Check if child is visited
            if child not in visited:
                child.g = current_node.g + 1
                visited.add(child)
                queue.append(child)

    return -1
Ejemplo n.º 2
0
    def shortest_path2(self, src):
        dst = [-1] * len(self.switches)
        prec = [None] * len(self.switches)
        explored = []
        queue = []
        dst[int(src.id)] = 0
        queue.append(src)
        queue.append(0)
        while queue:
            node = queue.pop(0)
            dist = queue.pop(0)

            if node not in explored:
                for edge in node.edges:

                    if edge.lnode == node:
                        to_node = edge.rnode
                    else:
                        to_node = edge.lnode

                    if to_node.type == "switch":
                        if dst[int(to_node.id)] == -1:
                            dst[int(to_node.id)] = dist + 1
                            prec[int(to_node.id)] = node.id
                            queue.append(to_node)
                            queue.append(dist + 1)

                explored.append(node)

        return dst, prec
Ejemplo n.º 3
0
def bipartite(adj):

    dist = [-1 for item in adj]
    CClevel = [0 for item in adj]

    cc = 0

    dist[0] = 0
    CClevel[0] = 0

    queue = [0]

    while queue:
        # Process phase
        cc = 1 - cc
        s = queue[0]
        for n in adj[s]:
            # Discover phase
            if dist[n] == -1:
                queue.append(n)
                dist[n] = dist[s] + 1
                CClevel[n] = cc
        queue.pop(0)

    for n, item in enumerate(adj):
        for nbr in item:
            if CClevel[n] == CClevel[nbr]:
                return 0
    return 1
Ejemplo n.º 4
0
def solution(progresses, speeds):
    queue = []
    answer = []
    count = 0

    # 큐에 삽입 (인덱스 접근 가능)
    for i in progresses:
        queue.append(100 - i)

    while len(queue) != 0:
        #queue가 빌 때까지 반복
        for x in range(0, len(queue)):
            queue[x] = queue[x] - speeds[x]

        while len(queue) != 0:
            if queue[0] > 0:
                #양수이면 그만
                break
            else:
                # 0이거나 음수이면
                queue.pop(0)
                speeds.pop(0)
                count += 1

        if count != 0:
            answer.append(count)
            count = 0

    return answer
def bfs(adj, q):
    #write your code here
    last_visit = []
    last_dist = []
    #for i in range(len(adj)):
    #	last_dist.append(-999)
    #dist[s] = 0
    queue = []
    queue = queue + q
    flags = [0] * len(adj)
    for i in queue:
        flags[i] = 1
    #print ("Relaxed:",queue)
    last_visit = last_visit + q
    while len(queue) != 0:
        u = queue[0]
        queue.pop(0)
        #print ("Current:",u)
        for v in adj[u]:
            #print ("Current Edge:",v)
            '''
			if v not in last_visit:
				queue.append(v) ##Add unvisited to the queue to process
				last_visit.append(v)
			'''
            if flags[v] != 1:
                queue.append(v)
                last_visit.append(v)
                flags[v] = 1
    #print (last_visit)
    return last_visit
Ejemplo n.º 6
0
 def run(self):
     while 1:
         try:
             queue.pop()
             print("Consumer: %s get a product" % self.name)
             time.sleep(2)
         except:
             print("Queue is empty!")
             time.sleep(2)
             print("Consumer: %s sleep 2 seconds" % self.name)
Ejemplo n.º 7
0
    def bellman(self, source, target):
        previous = {}
        distance = {}
        queue = []
        visited = {}
        count = {}

        cost_dict = self.__cost

        # we initialize the dictionaries
        for node in self.V:
            distance[node] = math.inf
            previous[node] = None
            count[node] = 0
            # no node is visited at the beginning
            visited[node] = False

        # the distance is 0 at the beginning
        distance[source] = 0

        # push the source in the queue
        queue.append(source)

        # the source vertex is marked as visited
        visited[source] = True

        # while the queue is not empty
        while queue:
            vertex = queue[0]
            queue.pop(0)
            visited[vertex] = False  # the vertex is marked as not visited
            for child in self._outbound:  # search through all its neighbours
                if distance[child] > distance[vertex] + cost_dict[
                    (vertex, child)]:
                    distance[child] = distance[vertex] + cost_dict[
                        (vertex, child)]  # update the distance
                    previous[child] = vertex

                    if visited[child] is False:
                        visited[child] = True  # child is marked as true
                        count[child] += 1
                        queue.append(child)  # push the child in the queue

                        # if the number of vertices is greater than the maximum number of vertices,
                        # we have negative cost cycle
                        # if count[child] >= len(self.graph.get_out()):
                        #     print("Negative cost cycle!")
                        #     return None

        # returns a pair distance, path
        msg = "no path"
        if distance[target] == math.inf:
            print("no path")
            return msg
        return (distance[target], self.get_path(source, target, previous))
Ejemplo n.º 8
0
 def on_message(self, ws, message):
     parsed_message = json.loads(message)
     message_type = parsed_message.get('method', 'unknown')
     if message_type not in self.messages:
         self.messages[message_type] = []
     queue = self.messages[message_type]
     if len(queue) == self.max_size:
         queue.pop(0)
     queue.append(parsed_message)
     try:
         self.handle_messages(parsed_message)
     except Exception as e:
         logger.exception(e)
Ejemplo n.º 9
0
def bfs(maze):
    """
    Runs BFS for part 1 of the assignment.

    @param maze: The maze to execute the search on.

    @return path: a list of tuples containing the coordinates of each state in the computed path
    """
    # reference: https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/
    queue = []
    visited = set()  # use a set to keep track of visited states
    queue.append([maze.start])
    goal = maze.waypoints[0]  # only one waypoint
    while queue:  # while our queue is not empty
        path = queue.pop(0)
        row, col = path[len(path) - 1]  # get last position in path
        if (row, col) in visited:
            continue
        visited.add((row, col))
        if ((row, col) == goal):
            return path
        for n in maze.neighbors(row, col):
            if n not in visited:
                queue.append(path + [n])  # will keep on appending to cur_path
    # return empty list if unsuccessful
    return []
def bfs(start, end):
    cost = 0
    visited = []
    prev = []
    queue = []
    queue.append(start)
    visited.append(start)
    prev.append(start)
    while queue:
        queue_start = queue.pop(0)
        for dist in graph[queue_start][2]:
            if dist[0] not in visited:
                cost += 1
                visited.append(dist[0])
                prev.append(queue_start)
                queue.append(dist[0])
                if dist[0] == end:
                    break
        else:
            continue
        break
    path = []
    last_val = visited[-1]
    while last_val != start:
        path.append(last_val)
        last_val = prev[visited.index(last_val)]
    else:
        path.append(last_val)
    path = path[::-1]
    return [cost, travel_cost(path), path]
Ejemplo n.º 11
0
def polygon_to_convex_polygons(polygon: List[Vec]) -> List[List[Vec]]:
    polygons = []
    queue = [list(polygon)]
    while len(queue) > 0:
        polygon = queue.pop()
        if len(polygon) < 3:
            continue
        for notch, (a,b,c) in enumerate(zip(np.roll(polygon,-1,0), polygon, np.roll(polygon,1,0))):
            if distance(a,c,b) < 0:
                break
        else:
            polygons.append(polygon) # Is already convex
            continue
        a,b,c = polygon[notch-1], polygon[notch], polygon[(notch+1)%len(polygon)]
        pointA, indexA = project_ray_polygon(polygon, a,b)
        pointC, indexB = project_ray_polygon(polygon, c,b)
        indexB -= 1

        if indexA - indexB == 1:
            polygon.insert(indexA, (pointA+pointC) / 2)
            if indexA < notch:
                notch += 1
            queue += [*split_polygon(polygon, notch, indexA)]
        else:
            queue += [*split_polygon(polygon, notch, (indexA + indexB) // 2)]
    return polygons
Ejemplo n.º 12
0
def dfs(maze):
    num_states_explored = 0
    start_position = maze.getStart()
    end_position = maze.getObjectives()
    visited, queue = list(), collections.deque([start_position])
    parent_map = {start_position: start_position}
    not_found = True
    while queue and not_found:
        num_states_explored += 1
        vertex = queue.pop()
        visited.append((vertex[0], vertex[1]))
        if (vertex[0], vertex[1]) == end_position[0]:
            not_found = False
            break
        for neighbour in maze.getNeighbors(vertex[0], vertex[1]):
            if neighbour not in queue and neighbour not in visited:
                queue.append(neighbour)
                parent_map[neighbour] = (vertex[0], vertex[1])

    # backtrack to find the trace
    parent_list = list()
    current = end_position[0]
    while current != start_position:
        parent_list.append(current)
        current = parent_map[current]
    parent_list.append(current)
    parent_list.reverse()
    return parent_list, num_states_explored
Ejemplo n.º 13
0
 def bfs_shortest_path(graph, start, goal):
     print("{} --- {} --- {}".format(graph, start, goal))
     # keep track of explored nodes
     explored = []
     # keep track of all the paths to be checked
     queue = [[start]]
 
     # return path if start is goal
     if start == goal:
         return "That was easy! Start = goal"
 
     # keeps looping until all possible paths have been checked
     while queue:
         # pop the first path from the queue
         path = queue.pop(0)
         # get the last node from the path
         node = path[-1]
         if node not in explored:
             neighbours = graph[node]
             # go through all neighbour nodes, construct a new path and
             # push it into the queue
             for neighbour in neighbours:
                 new_path = list(path)
                 new_path.append(neighbour)
                 queue.append(new_path)
                 # return path if neighbour is goal
                 if neighbour == goal:
                     return new_path
 
             # mark node as explored
             explored.append(node)
 
     # in case there's no path between the 2 nodes
     return "So sorry, but a connecting path doesn't exist :("
Ejemplo n.º 14
0
 def simulateData(self,times):
     for t in range(times):
         temp={}
         for n in self.noParent:#prior
             temp[n]='F'
             rowT=self.graph[n].probabilityTable['T']
             if random.random()<=rowT[3]:
                 temp[n]='T'
                 rowT[1]+=1
             rowT[2]+=1
             a=rowT[1]/rowT[2]
             rowT[0]=math.floor(a*100)/100
         queue=list(self.parent)#clone it and become a queue
         while queue:#is not empty
             q=queue.pop(0)#pop from head
             if set(self.parent[q]).issubset(temp):#if all parents are ready
                 st=''
                 temp[q]='F'
                 table=self.graph[q].probabilityTable
                 for i in self.parent[q]:
                     st+=str(temp[i])
                 if random.random()<=table[st][3]:
                     temp[q]='T'
                     table[st][1]+=1
                 table[st][2]+=1
                 a=table[st][1]/table[st][2]
                 table[st][0]=math.floor(a*1000)/1000
             else:
                 queue.append(q)#add to tail
     #after all simulating, update the prior probability of each node  (without given condition)
     self.generatePriorProbability()
Ejemplo n.º 15
0
 def isReachable(self, agent_i, agent_j):
     '''
     if isReachable form agent_i to agent_j
     '''
     self.BuildReachableMatrix()
     # Create a queue for BFS
     queue = []
     # Mark the source node as visited and enqueue it
     visited = []
     for i in range(self.n):
         visited[i].append(False)
     queue.append(agent_i)
     visited[agent_i] = True
     while queue:  #q is not empty
         #Dequeue a vertex from queue
         n = queue.pop(0)
         # If this adjacent node is the destination node,
         # then return true
         if self.Matrix[n, agent_j] == True:
             return True
         #  Else, continue to do BFS
         for i in self.dictReach[n]:
             if visited[i] == False:
                 queue.append(i)
                 visited[i] = True
     return False
Ejemplo n.º 16
0
    def validTree(self, n, edges):
        # 检查graph上的边是否满足构成树的基本要求
        if len(edges) != n - 1:
            return False

        # 建立邻接字典,存储两点之间的联通情况
        neighbors = collections.defaultdict(list)
        for u, v in edges:
            neighbors[u].append(v)  # 注意这里需要使用append,因为一点可能与多点相连
            neighbors[v].append(u)

        # 建立已遍历点的字典以及队列
        visits = {}
        queue = []
        queue.append(0)
        visits[0] = True

        # 依次根据连通节点遍历图中所有可能节点
        while queue:
            val = queue.pop(0)
            visits[val] = True

            for i in neighbors[val]:
                if not visits[i]:
                    visits[i] = True
                    queue.append(i)
        # 验证通过邻接边所遍历的所有节点是否等于图中的所有节点
        return len(visits) == n
Ejemplo n.º 17
0
 def generatePriorProbability(self):
     self.order=[]#the order that all parents of node are ready
     for n in self.noParent:
         self.graph[n].probability=self.graph[n].probabilityTable['T'][0]
         self.order.append(n)
     queue=list(self.parent)#clone it and become a queue
     while queue:#is not empty
         q=queue.pop(0)#pop from head
         if set(self.parent[q]).issubset(self.order):#if all parents are ready
             self.order.append(q)
             nu=0#numerator
             de=0#denominator
             for k in self.graph[q].probabilityTable:
                 if k != q:#skip title row
                     pro=1
                     pro2=1
                     for m in range(len(k)):
                         if k[m]=='T':
                             pro*=self.graph[self.parent[q][m]].probability
                         elif k[m]=='F':
                             pro*=(1-self.graph[self.parent[q][m]].probability)
                     pro2*=pro*(1-self.graph[q].probabilityTable[k][0])
                     pro*=self.graph[q].probabilityTable[k][0]#happening ratio*simulated ratio
                     nu+=pro
                     de+=pro2
             self.graph[q].probability=nu/(nu+de)
         else:
             queue.append(q)
Ejemplo n.º 18
0
    async def turn_queue(self, queue_list):
        # Might need to revise later.
        queue = []
        for i in queue_list:
            queue.append(i)
        stack = []
        for i in range(len(queue)):
            self.queue_preview = [piece.get_name() for piece in queue]
            self.queue_preview.reverse()
            current_piece = queue.pop()
            print(queue)
            self.current_piece = current_piece

            # await self.send_current_piece_embed(current_piece)
            # add to stack from queue the piece with the highest speed and perform its action one a time
            stack.append(current_piece)
            if (stack[i].get_hp() > 0):
                current_piece.toggle_active()
                await self.update_all(conc=True)
                await stack[i].get_action(self.duel_helper)
            current_piece.toggle_active()
            if (self.force_check == True):  #For detecting a QUIT early.
                print("checking.")
                obituary = self.entity_clear(quit=True)
                is_end = self.check_game_end(
                )  #Checks if it is permissible to end the game here.
                if is_end:
                    #Early termination.  Will do for now.
                    self.game_is_active = False
                    return stack
                self.force_check = False
        return stack  # stack will now contain entity_list from highest to lowest speed
def distance(adj, cost, s, t):
    #write your code here
    #initialize
    max_weight = 1
    for weight in cost:
        max_weight += sum(weight)
    weight = [max_weight for _ in range(len(adj))]
    relaxed = [0 for _ in range(len(adj))]
    queue = [(0, s)]
    weight[s] = 0

    #bfs
    while queue:
        queue.sort()
        tempNode = queue.pop(0)[1]
        for i, end_node in enumerate(adj[tempNode]):
            if relaxed[end_node] != 2:
                tweight = cost[tempNode][i] + weight[tempNode]
                if weight[end_node] > tweight:
                    if relaxed[end_node] == 1:
                        queue.remove((weight[end_node], end_node))
                    weight[end_node] = tweight
                    queue.append((weight[end_node], end_node))
                    relaxed[end_node] = 1
                if relaxed[end_node] == 0:
                    queue.append((weight[end_node], end_node))
                    relaxed[end_node] = 1
        relaxed[tempNode] = 2
    if weight[t] < max_weight:
        return weight[t]

    return -1
Ejemplo n.º 20
0
def BFS_or_DFS(G, start, goal, bfs):
    visited = set()
    prev = dict()
    prev[start] = None

    queue = [start]

    while queue:
        cur = queue.pop()
        visited.add(cur)

        if cur == goal:
            break

        for neighbor in G.neighbors(cur):
            if neighbor not in visited:
                if bfs:
                    queue.insert(0, neighbor)
                else:
                    queue.append(neighbor)
                prev[neighbor] = cur

    path = []
    cur = goal
    while cur:
        path.insert(0, cur)
        cur = prev[cur]

    return path, list(visited)
Ejemplo n.º 21
0
def bfs_algorithm(draw,grid,start_pos,end_pos):
    visited = []  # List to keep track of visited nodes.
    queue = []  # Initialize a queue
    visited.append(start_pos)
    queue.append(start_pos)
    came_from = {}

    while queue:
        current = queue.pop(0)
        current.make_closed()
        if current == end_pos:
            reconstruct_path(came_from,end_pos,draw)
            end_pos.make_end()
            return True

        for neighbour in current.neighbors:

            if neighbour not in visited:
                came_from[neighbour] = current
                visited.append(neighbour)
                neighbour.make_open()
                queue.append(neighbour)
        draw()
        if current != start_pos:
            current.make_closed()
    return False
Ejemplo n.º 22
0
def distance(adj, s, t):
    #write your code here

    #initial params
    ini_dis = len(adj) + 1
    dis = [ini_dis for _ in range(len(adj))]
    visited = [0 for _ in range(len(adj))]
    #start node
    queue = [s]
    dis[s] = 0
    d = 0

    #bfs
    while queue:
        time = len(queue)
        for _ in range(time):
            temp_node = queue.pop(0)
            for end_node in adj[temp_node]:
                if visited[end_node] == 0:
                    visited[end_node] = 1
                    queue.append(end_node)
            dis[temp_node] = d
            visited[temp_node] = 2
        d += 1

    if dis[t] < ini_dis:
        return dis[t]
    return -1
Ejemplo n.º 23
0
    def BFS(self, list, s):
        a = 0

        visited = [False] * (self._n)
        queue = []
        edges = []
        queue.append(s)
        visited[s] = True

        while queue:
            s = queue.pop(0)
            print(s, " ")
            list.append(s)
            a += 1
            for i in self._dictIn[s]:
                if visited[i] == False:
                    edges.append([s, i])
                    queue.append(i)
                    visited[i] = True
                elif visited[i] == True and [i, s] not in edges:
                    edges.append([s, i])
        print("")
        # if (a!=1000):
        #    print (a)
        # print (a)
        return [list, edges]
Ejemplo n.º 24
0
def shortet_paths(adj, cost, s, distance, reachable, shortest):
    BellMan_Ford(adj, cost, distance, s, reachable)
    ncycle = []
    for u in range(len(adj)):
        for v, w in zip(adj[u], cost[u]):
            if distance[v] > distance[u] + w and distance[u] != 10**19:
                distance[v] = distance[u] + w
                ncycle.append(v)
    if ncycle:
        queue = []
        visited = [False] * (len(adj))
        while ncycle:
            s = ncycle.pop(0)
            if visited[s] == True:
                continue
            queue.append(s)
            visited[s] = True
            shortest[s] = 0
            while queue:
                t = queue.pop(0)
                for u in adj[t]:
                    if visited[u] == False:
                        visited[u] = True
                        shortest[u] = 0
                        queue.append(u)
    pass
Ejemplo n.º 25
0
    def lengthOfLongestSubstring(self, s):
        longest = 0
        queue = []
        for c in s:
            if c not in queue:
                queue.append(c)
            else:
                while queue[0] != c:
                    queue.pop(0)
                queue.pop(0)
                queue.append(c)

            if len(queue) > longest:
                longest = len(queue)

        return longest
def shortet_paths(adj, cost, s, distance, reachable, shortest):
    vertices = len(adj)
    distance[s] = 0
    reachable[s] = 1
    queue = []
    visited = [False] * vertices

    for _ in range(vertices - 1):
        for u in range(vertices):
            i = 0  # magic variable
            for v in adj[u]:
                if distance[v] > distance[u] + cost[u][i]:
                    distance[v] = distance[u] + cost[u][i]
                    reachable[v] = 1
                i += 1

    for u in range(vertices):
        i = 0  # magic variable
        for v in adj[u]:
            if distance[v] > distance[u] + cost[u][i]:
                if v not in queue:
                    queue.append(v)
            i += 1

    while queue:
        u = queue.pop(0)
        visited[u] = True
        shortest[u] = 0
        for v in adj[u]:
            if not visited[v] and v not in queue:
                queue.append(v)
Ejemplo n.º 27
0
 def add(self, elem):
     """
     为树添加节点
     :param elem:
     :return:
     """
     node = TreeNode(elem)
     # 如果树是空的,则对根节点赋值
     if self.root == None:
         self.root = node
     else:
         queue = list()
         queue.append(self.root)
         while queue:
             # 弹出队列的第一个元素
             cur = queue.pop(0)
             if cur.left == None:
                 cur.left = node
                 return
             elif cur.right == None:
                 cur.right = node
                 return
             else:
                 # 如果左右子树都不为空,往判断列表加入子树,循环进行子树的判断
                 queue.append(cur.left)
                 queue.append(cur.right)
def bfs(tree, start, end, visit):
    global count
    # maintain a queue of paths
    queue = []
    # push the first point into the queue
    queue.append(start)
    print('my start is %s', start)
    print('my end is %s', end)
    print('bfs finding...')
    while queue:
        # get the first point from the queue
        #         print('checking queue')
        #         print(queue)
        node = queue.pop(0)

        #         print('checking node')
        #         print(node)

        # path found
        if node == end:
            return
        adjacent = tree.get(node)
        #         print(adjacent)
        #         print(visit[node[0]][node[1]])
        # up, right, down, left, parent[0:up,1:right,2:down,3:left]
        if (adjacent[0] == 1) and (visit[node[0] - 1][node[1]] == 0):  #UP
            #             print('if1')
            #             print(tree.get((1,24)))
            newnode = (node[0] - 1, node[1])
            queue.append(newnode)
            maze_tree[newnode][4] = 2
            visit[newnode[0]][newnode[1]] = 1
            count = count + 1

        if (adjacent[1] == 1) and (visit[node[0]][node[1] + 1] == 0):  #right
            #             print('if2')
            #             print(tree.get((1,24)))
            newnode = (node[0], node[1] + 1)
            queue.append(newnode)
            maze_tree[newnode][4] = 3
            visit[newnode[0]][newnode[1]] = 1
            count = count + 1

        if (adjacent[2] == 1) and (visit[node[0] + 1][node[1]]) == 0:  #down
            #             print('if3')
            #             print(tree.get((1,24)))
            newnode = (node[0] + 1, node[1])
            queue.append(newnode)
            maze_tree[newnode][4] = 0
            visit[newnode[0]][newnode[1]] = 1
            count = count + 1

        if (adjacent[3] == 1) and (visit[node[0]][node[1] - 1] == 0):  #left
            #             print('if4')
            #             print(tree.get((1,24)))
            newnode = (node[0], node[1] - 1)
            queue.append(newnode)
            maze_tree[newnode][4] = 1
            visit[newnode[0]][newnode[1]] = 1
            count = count + 1
Ejemplo n.º 29
0
def distance(adj, s, t):

    n = len(adj)
    queue = []
    visited = set()
    path = []

    queue.append([s])

    dist = 0

    while (len(queue) > 0):
        path = queue.pop(0)

        last_vertex = path[-1]

        if last_vertex == t:
            # print(path)
            dist = len(path) - 1

        elif last_vertex not in visited:
            for w in adj[last_vertex]:
                new_path = list(path)
                new_path.append((w))
                queue.append(new_path)
            visited.add(last_vertex)

    if dist != 0:
        return dist
    else:
        return -1
Ejemplo n.º 30
0
def bfs_connected_component(graph, start):
    # keep track of all visited nodes
    explored = []
    # keep track of nodes to be checked
    queue = [start]

    levels = {}  # dictionary to keep track of levels
    levels[start] = 0  # depth of start node is 0

    visited = [start]  # to avoid inserting the same node twice into the queue

    # keep looping until there are nodes still to be checked
    while queue:
        # pop shallowest node (first node) from queue
        node = queue.pop(0)
        explored.append(node)
        neighbours = graph[node]

        # add neighbours of node to queue
        for neighbour in neighbours:
            if neighbour not in visited:
                queue.append(neighbour)
                visited.append(neighbour)

                levels[neighbour] = levels[node] + 1
                # print(neighbour, ">>", levels[neighbour])

    print(levels)

    return explored
def bfs(node, v):
    queue = []
    v.group = bfs.group
    #shortest_path_tree T = empty
    search(node, v, queue)
    while len(queue) != 0:
        w = queue.pop(0)
        search(node, node[w], queue)
def bfs(node, v, inf_v):
	queue = []
	v.group = bfs.group
	#shortest_path_tree T = empty
	search(node, v, queue)
	inf_v.append(v.value) # Appending the start point(not in queue).
	while len(queue) != 0:
		w = queue.pop(0)
		inf_v.append(w.value)
		search(node, w, queue)
Ejemplo n.º 33
0
 def bfs (self, myGraph, start, end):
     queue = [(start, [start])]
     while queue:
         (vertex, path) = queue.pop(0)
         try: 
             for next in myGraph[vertex]:
                 if next[0] == end:
                     return path + [next]
                 else:
                     queue.append((next, path +[next]))
         except KeyError:
             continue
def search(start, goal):
    queue = StateQueue()
    queue.push(Move(start))
    while not queue.empty():
        current = queue.pop()
        # print(current[1].state)
        
        # current[1] is necessary because we put the move object in queue using (f(n), move) tuple
        if cmp(current[1].state, goal) == 0: 
            return current[1]
        else:
            successors = current[1].move()
            for i in successors:
                # print("pushed", i.state)
                queue.push(i)
    return None
def distance(adj, s, t):
    queue = []
    distance = {k:-1 for k in range(0, len(adj))}

    #make s initial node
    distance[s] = 0
    queue.append(s)
    while len(queue):
        v = queue.pop(0)
        for edge in adj[v]:
            if distance[edge] == -1:
                distance[edge] = distance[v] + 1
                queue.append(edge)
                if edge == t:
                    return distance[edge]
    return -1
Ejemplo n.º 36
0
def bfs(graph, startnode, endnode):

    queue = []
    queue.append([startnode])
    while queue:

        path = queue.pop(0)

        node = path[-1]

        if node == endnode:
            return path
        for adjacent in graph.get(node, []):
            new_path = list(path)
            new_path.append(adjacent)
            queue.append(new_path)
Ejemplo n.º 37
0
def BFTravel2list(rootNode):
    queue = Queue()
    queue.push(rootNode)

    lsBlock = []
    while queue.isEmpty() == False:
        node = queue.pop()
        if node.userData == None:
            info = DiffInfo()
            node.userData = info
        node.userData.fingerPrint = buildFingerPrint(node)
        lsBlock.append(node)

        # print ("%x : %s") % (node.name, node.userData.fingerPrint)
        for childOffset in node.children:
            childNode = node.children[childOffset]
            if childNode.userData == None:
                info = DiffInfo()
                info.parent = node
                childNode.userData = info
                queue.push(childNode)

    return lsBlock
Ejemplo n.º 38
0
def work():
    tweets,finished = queue.pop(100)
    if not tweets: return
    db.save(*filter(None,map(analyze, tweets)))
    finished()
    return len(tweets)
Ejemplo n.º 39
0
def _client():
  item = queue.pop()
  if item:
    return flask.render_template(item.template, item=item)
  return flask.render_template('empty.html')