我有一个节点数组,这些节点彼此相连。
我有以下节点网络。 这里的0是起点,我想尽可能多地走过节点,并且每个节点只走一次。在从0到目标节点的旅程中,我只希望有一个奇数编号的节点(例如1、3、5、7)。现在我需要找出从我的起始位置0可以行驶的最长路线。
示例:
int[] array = { 0, 9, 0, 2, 6, 8, 0, 8, 3, 0 };
在上图中,以下是可能性:0 -> 6 -> 4 (valid path, length = 3 nodes)
0 -> 9 -> 1 (Not valid path, length as we have 2 odd numbers here 1 & 9)
0 -> 2 -> 3 -> 8 (valid path, length = 4 nodes)
0 -> 2 -> 3 -> 8 -> 5 (Not valid path as we have 2 odd numbers here 3 & 5)
0 -> 2 -> 3 -> 8 -> 7 (Not valid path as we have 2 odd numbers here 3 & 7)
So the answer is 4 for this input.
以下是我正在尝试的程序。
public int process(int[] array) {
int count = array.length;
ArrayList<Integer>[] branches = new ArrayList[count];
for (int i = 0; i < count; i++) {
branches[i] = new ArrayList<>();
}
int begin = 0;
for (int i = 0; i < count; i++) {
if (array[i] != i) {
branches[i].add(array[i]);
branches[array[i]].add(i);
}
}
Arrays.stream(branches).forEach(System.out::println);
Queue<Network> networkQueue = new LinkedList<Network>();
ArrayList<Integer> networkList = branches[begin];
networkList.forEach(value -> {
Network net = new Network(0, value);
networkQueue.add(net);
});
System.out.println("printing starting nodes.......");
List<Network> nodes = new ArrayList<>();
for (Network n : networkQueue) {
nodes.add(n);
System.out.println(n.value + " : " + n.road);
}
int result = 0;
return result;
}
class Network {
int road, value;
public Network(int road, int value) {
this.road = road;
this.value= value;
}
}
该程序会打印从起始点0开始的分支和节点:
[2, 6, 9]
[9]
[0, 3]
[2, 8]
[6]
[8]
[4, 0]
[8]
[5, 7, 3]
[1, 0]
printing starting nodes.......
2 : 0
6 : 0
9 : 0
我在寻找最长的路径上遇到了困难,下一步该如何进行这个程序,请在这里帮助我。
0
开始,我可以前往其他节点1,2,3,4,5,6,7,8,9
。 - learner