示例#1
0
    def BFS(self, graph, start, end, q, numRoutes):

        temp_path = [start]
        valid_paths = []
        numValidPaths = 0
        maxCycles = 80000
        cycleNum = 0

        q.enqueue(temp_path)
        sys.stdout.write("Working...")
        while not q.isEmpty():
            if cycleNum >= maxCycles:
                break
            temp_path = q.dequeue()
            last_node = temp_path[len(temp_path) - 1]
            # for i in temp_path:
            # 	sys.stdout.write(i.getCode() + " ->")
            # sys.stdout.write("\n")
            if last_node.getCode() == end.getCode():
                numValidPaths += 1
                sys.stdout.write("Valid path: ")
                new_temp = deepcopy(temp_path)
                #construct a route object
                tempRoute = Route(temp_path[0])
                for j in range(1, len(temp_path)):
                    tempRoute.addAirport(temp_path[j])
                valid_paths.append(tempRoute)
                # for i in temp_path:
                # 	sys.stdout.write(i.getCode() + " ->")
                # sys.stdout.write("\n")
                if numValidPaths > numRoutes:
                    return valid_paths
            lastNodeConnections = last_node.getConnections()
            for link_node in range(len(lastNodeConnections)):
                newLinkFoundInPath = False
                for k in range(len(temp_path)):
                    if lastNodeConnections[link_node].getAirport().getCode() == temp_path[k].getCode():
                        newLinkFoundInPath = True
                        break
                if not newLinkFoundInPath:
                    new_path = temp_path + [lastNodeConnections[link_node].getAirport()]
                    q.enqueue(new_path)
            cycleNum += 1
            if cycleNum % 10000 == 0:
                print(cycleNum)
        sys.stdout.write("Done")
        return valid_paths