【问题标题】:Count paths from one point to another in array recursion without repeating a cell在数组递归中计算从一个点到另一个点的路径而不重复一个单元格
【发布时间】:2014-12-27 20:43:09
【问题描述】:

当我可以从每个单元格(在数组边界内)向右、向左、向下或向上移动时,我需要计算数组中从一个单元格到另一个单元格的路径数。

如何避免在检查路径时重复已通过的单元格?还有一条规则:

您不能使用其他数组、循环和静态变量。

我怎样才能从这里继续?

我的递归函数:

public static int calcPath(int [][] a, int currentx, int currenty, int destx, int desty)
{
    if (currentx == destx && currenty == desty)
        return 1;
    if(!bounds(a,currentx,currenty)) // if the cell isnt in the array bounds
        return 0;

    return  calcPath(math,currentx+1,currenty,destx,desty) +
             calcPath(math,currentx-1,currenty,destx,desty)+
              calcPath(math,currentx,currenty+1,destx,desty)+
               calcPath(math,currentx,currenty-1,destx,desty);
}

【问题讨论】:

  • 它可能会帮助我避免重复返回最后一个单元格,但如果我沿着圆形路径(右下左上)移动,我仍然可能会重复一次我已经通过的单元格。

标签: java arrays recursion maze


【解决方案1】:

绕过一组已经访问过的单元格。最好的方法是创建一个类来封装 x 和 y if 一个单元格并实现一个比较坐标的 equals() 方法。但是,您可以通过为这两个值创建一个唯一的值来“破解”它。

破解版如下所示:

public static int calcPath(int [][] a, int currentx, int currenty, int destx, int desty, Set<Integer> visited) {
    int key = 1000 * currentx + currenty; // unique for x, y
    if (visited.contais(key))
        return 0;
    if (currentx == destx && currenty == desty)
        return 1;
    if(!bounds(a,currentx,currenty)) // if the cell isnt in the array bounds
        return 0;
    Set<Integer> s = new HashSet<Integer>(visited);
    s.add(key);
    return  calcPath(math,currentx+1,currenty,destx,desty,s) +
         calcPath(math,currentx-1,currenty,destx,desty,s)+
          calcPath(math,currentx,currenty+1,destx,desty,s)+
           calcPath(math,currentx,currenty-1,destx,desty,s);
}

请注意,递归时必须创建一个新集合,以免污染调用者堆。

对于初始调用,传入一个空 Set。

【讨论】:

  • 关键公式必须是 1000*currentx + currenty 还是我错了?
  • @marie 我没有仔细看,所以你可能是对的。检查哪个也可能无关紧要!
  • 但是如果我使用函数包含它意味着我使用循环,因为这个函数是基于循环的不是吗?
  • 不,HashSet 使用哈希查找,它的速度为 O(1)(非常快!)
  • 另一个问题,为什么要在函数中再次初始化hashset?为什么不将密钥添加到已访问的哈希集并在递归中发送该集?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-01
  • 2019-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多