考虑最大距离

时间:2017-12-16 17:24:21

标签: python algorithm graph

所以这是我的问题:

我正在尝试找到从C到C的所有不同路径,其中最大距离为30。

我认为我的停止条件存在问题,但我已经尝试了这么久以至于我看不出有什么问题(打印2但应该是7)。

我的问题在Java中有一个实现,但我想用Python(问题10)来实现:link

我的代码:

            from collections import defaultdict, deque


        class Graph(object):
            def __init__(self):
                self.nodes = set()
                self.edges = defaultdict(list)
                self.distances = {}

            def add_node(self, value):
                self.nodes.add(value)

            def add_edge(self, from_node, to_node, distance):
                self.edges[from_node].append(to_node)
                self.distances[(from_node, to_node)] = distance

        def are_these_nodes_adjacents(from_node, to_node):
            return to_node in graph.edges[from_node]

        def count_distance(graph, u, v, k, max_distance):
            if(k > 0 and u == v and k != max_distance): 
                return 1
            if(k > 0 and are_these_nodes_adjacents(u, v)): 
                return 1
            if(k <= 0): 
                return 0

            count = 0

            for i in ['A', 'B', 'C', 'D', 'E']:
                if(are_these_nodes_adjacents(u, i)):
                        count += count_distance(graph, i, v, k-graph.distances[(u, i)], max_distance)
            return count

        if __name__ == '__main__':
            graph = Graph()

            for node in ['A', 'B', 'C', 'D', 'E']:
                graph.add_node(node)

            graph.add_edge('A', 'B', 5)
            graph.add_edge('B', 'C', 4)
            graph.add_edge('C', 'D', 8)
            graph.add_edge('D', 'C', 8)
            graph.add_edge('D', 'E', 6)
            graph.add_edge('A', 'D', 5)
            graph.add_edge('C', 'E', 2)
            graph.add_edge('E', 'B', 3)
            graph.add_edge('A', 'E', 7)

            u = 'C'
            v = 'C'
            k = 30
            print(count_distance(graph, u, v, k, k))

1 个答案:

答案 0 :(得分:2)

代码中的以下条件:

class Employee
    {
        int value;

        Employee(int value)
        {
            this.value = value;
        }

        public void checkValue(int value1, int value2)
        {
            // i want to check here value1 & value2 is there or not in array
            // Or in another word I want to retrieve every element of the array in this method.   
        }
    }

    public class Test
    {
        public static void main(String arg[])
        {
            Employee e1[] = { new Employee(100), new Employee(200), new Employee(300) };

            e1.checkValue(100, 200);

        }
    }

当您再次返回节点C时,您将返回并停止搜索。而不是这样做,你需要添加1来计数,并继续搜索。

您应该删除以下条件:

if(k > 0 and u == v and k != max_distance):  
         return 1

你为什么拥有它?

这是生成的代码,根据需要打印7:

if(k > 0 and are_these_nodes_adjacents(u, v)): 
                return 1