具有异常的递归Java函数

时间:2018-04-28 21:44:57

标签: java recursion

我有一张带有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;
}

1 个答案:

答案 0 :(得分:1)

下面的内容应该可以解决问题。我将留给你实现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>());
}