def levelOrder(self):
     q = Queue()
     q.enqueue(self.root)
     while q.size() > 0:
         treeNode = q.dequeue()
         print(treeNode.key)
         if treeNode.leftChild:
             q.enqueue(treeNode.leftChild)
         if treeNode.rightChild:
             q.enqueue(treeNode.rightChild)
コード例 #2
0
ファイル: word_ladder.py プロジェクト: Farheen2302/ds_algo
def bfs(g, start):
    queue = Queue()
    queue.enqueue(start)
    start.setPred(None)
    while (queue.size() > 0):
        current = queue.dequeue()
        for nbr in current.getConnections():
            if nbr.getColor() == 'white':
                nbr.setColor('grey')
                nbr.setPred(current)
                queue.enqueue(nbr)
        current.setColor('black')
コード例 #3
0
def bfs(graph, start, debug=False):
      """
      Breadth First Search (BFS)
       Given a node in a graph, BFS will find all nodes connected to this
      node. The distance between nodes is measured in HOPS. It will find
      all nodes at distance 'k' before finding any nodes at a further
      distance. It will return the full list of connected nodes.
       PseudoCode:
       BFS(G,s)
       for each vertex u in V[G] - {s} do
        state[u] = WHITE
        predecessor[u] = nil
      state[s] = GRAY
      predecessor[s] = nil
      QUEUE = {s}
      while QUEUE != 0 do
        u = dequeue[Q]
        process vertex u as desired
        for each v in Adjacent[u] do
          process edge (u,v) as desired (e.g. distance[v] = distance[u] + 1)
          if state[v] = WHITE then
            state[v] = GRAY
            predecessor[v] = u
            enqueue[Q,v]
        state[u] = BLACK
      """
      result = []
      for v in graph.getVertices():
          a_vertex = graph.getVertex(v)
          a_vertex.__classname__ = 'MyVertex'
          a_vertex.setColor(MyVertex.WHITE)
          a_vertex.setDistance(0)
          a_vertex.setPred(None)

      start.setDistance(0)
      start.setPred(None)
      vertex_queue = Queue()
      vertex_queue.enqueue(start)
      while (vertex_queue.size() > 0):
          current_vertex = vertex_queue.dequeue()
          result.append(current_vertex)
          if debug:
              print(current_vertex)
          for v in current_vertex.getConnections():
              if v.getColor() == MyVertex.WHITE:
                  v.setColor(MyVertex.GRAY)
                  v.setDistance(current_vertex.getDistance() + 1)
                  v.setPred(current_vertex)
                  vertex_queue.enqueue(v)
          current_vertex.setColor(MyVertex.BLACK)
      return result
コード例 #4
0
def bfs(begin):  #x,y为初始点的坐标
    q = Queue()
    q.enqueue(begin)
    while q.size() > 0:
        now = q.dequeue()
        x = now[0]
        y = now[1]
        vis[x][y] = 2
        if now == [5, 5]:
            print("Yes")
            return
        for i in range(4):
            x = now[0] + xi[i]
            y = now[1] + yi[i]
            if 0 <= x <= 5 and 0 <= y <= 5 and map_[x][y] == 0 and vis[x][
                    y] == 0:
                q.enqueue([x, y])
    print("No")
    return
コード例 #5
0
def simulation(numSeconds, pagesPerMinute):

    labprinter = Printer(pagesPerMinute)
    printQueue = Queue()
    waitingtimes = []

    for currentSecond in range(numSeconds):
        if newPrintTask():
            #print("cursecond is %d"%currentSecond)
            task = Task(currentSecond)
            printQueue.enqueue(task)

        if (not labprinter.busy()) and \
            (not printQueue.isEmpty()):
            nexttask = printQueue.dequeue()
            waitingtimes.append( \
                nexttask.waitTime(currentSecond))
            labprinter.startNext(nexttask)
        labprinter.tick()
    averageWait = sum(waitingtimes) / len(waitingtimes)
    print("Avg wait %6.2f secs %3d tasks remaining." %
          (averageWait, printQueue.size()))
コード例 #6
0
        self.current_car_time -= 1
        if self.current_car_time == 0:
            return False  # 洗完需要换车
        else:
            return True


washer = Washer()
car_queue = Queue()  # 洗车排队,只有10个车位
current: Car = None  # 空档状态
wait_time = []
# 模拟两小时
randomor = random.Random()
for second in range(7200):
    if randomor.randrange(
            600) == 0 and car_queue.size() < 20:  # 概率上600秒来一辆车,概率运算一定会一直进行
        new_car = Car()
        new_car.timestamp = second  # 标记开始等待时间
        car_queue.enqueue(new_car)  # 排到队尾

    # 洗车
    # if washer.current_car_time == 0 and not car_queue.isEmpty():  # 无车在洗,队列有车
    #     current = car_queue.dequeue()  # 队尾为下一个车
    if not washer.wash(current):  # 无车在洗
        if not car_queue.isEmpty():  # 有车可换
            current = car_queue.dequeue()
            wait_time.append(second - current.timestamp)  # 存储车辆等待时间
        else:  # 无车可换
            current = None

print('总共洗车:', len(wait_time), '辆,平均等待时间:',