给定int [] TO数组和int []从具有节点数和边数的数组中,找到最长路径

时间:2017-11-22 01:15:29

标签: java algorithm graph

我在面试编码时被问到了这个问题。虽然我没有成功完成这项任务,但我想知道是否有人可以帮助我理解如何做到这一点。

问题: 您将获得节点数和边数。有了这个,您将获得两个数组:g_From[]g_To[]。你要找到两个节点之间的最大距离。

输入:

第一行包含两个整数,节点数n和边e。

Next e lines consists of g_From and g_To

示例:

5 6 //Number of Nodes = 5, edges = 6. Following 6 line are to-from

1 2 //g_from[0] = 1, g_to[0] = 2 => from node 1 to node 2

1 3 //g_from[1] = 1, g_to[1] = 3 => from node 1 to node 3

2 3 //g_from[2] = 2, g_to[2] = 3 => from node 2 to node 3

2 4 //g_from[3] = 2, g_to[3] = 4 => from node 2 to node 4

3 4 //g_from[4] = 3, g_to[4] = 4 => from node 3 to node 4

4 5 //g_from[5] = 4, g_to[5] = 5 => from node 4 to node 5 

Output:
4

Explanation:
As you can see from the inputs there are many ways to traverse
for example: 

1->3->4->5

2->3->4->5

但最长的路线是: 1→2→3→4-→5

距离是5-1 = 4,回答!

2 个答案:

答案 0 :(得分:0)

创建两个int数组,即g_from和g_to
通过调用函数遍历创建函数遍历来遍历数组,并将toNode作为参数放置,每次加1到长度
创建函数findLongestRoute以找到最长路径

private int[] g_from = new int[6];
private int[] g_to = new int[6];

public Integer traverse(Integer fromNode,Integer length) {
    for(int i = 0; i < g_from.length; i++) {
        if(g_from[i] == fromNode) {
            return traverse(g_to[i],++length);
        }
    }
    return length;
}

public Integer findLongestRoute() {
    int l = 0;

    for(int i = 0; i < g_from.length; i++) {
        int length = traverse(g_from[i],0);
        if(length > l) {
            l = length;
        }
    }

    return l;
}

答案 1 :(得分:0)

由于成本是积极的,所以Dijsktra会起作用。

将值从正反转为负,然后运行最短路径算法。

建立的路径将是最长的,最终取得成本的绝对价值。