我有一个带有IDS&的表他们的邻居需要创建一个递归函数,该功能从开始ID到结束ID >,而无需两次越过同一点。假设启动ID为1,端ID为3。唯一可能的完整路径是(1,2,3(&(1,5,3(
{1 | 2,5}
{2 | 1,3,4,5}
{3 | 2,5}
{4 | 2}
{5 | 1,2,3}
当前代码(通过@Jeffrey Phillips Freeman(
List<Integer> searchHops(int from, int to, List<Integer> seen) {
seen.add(from);
if (from == to)
return new ArrayList<Integer>(Arrays.asList(from));
for (int neighbor : getNeighbors(from))
if (!seen.contains(neighbor)) {
List<Integer> result = searchHops(neighbor, to, seen);
if (result != null) {
result.add(0, from);
return result;
}
}
return null;
}
沿着以下内容的某些内容应该可以解决问题。我将留给您实施getneighbors方法。您还应该调用该方法,看到的是一个空的arraylist
private List<Integer> searchHops(int from, int to, List<Integer> seen) {
seen.add(from);
if( from == to )
return new ArrayList<Integer>(Arrays.asList(from));
for(int neighbor : getNeighbors(from) )
if( !seen.contains(neighbor) ) {
List<Integer> result = searchHops(neighbor, to, seen);
if(result != null) {
result.add(0, from);
return result;
}
}
return null;
}
//actual entry point
public List<Integer> searchHops(int from, int to) {
return searchHops(from, to, new ArrayList<Integer>());
}