【问题标题】:Fixing a recursive method修复递归方法
【发布时间】:2013-06-23 13:15:32
【问题描述】:

我正在尝试编写一个使用递归方法查找从二维数组开始到结束的路径数的程序。这些步骤应该从 [0][0] 开始直到结束。数组由 0 到 99 之间的整数填充。

对于数组中的每个数字都可以向前移动两个不同的步骤:例如,如果 [0][0] 是 21 ,则下一步可能是 [0+2][0+1] 或 [0+1][0 +2] 。 该方法应返回到达终点的不同路径的数量。

这是我的代码:

编译过程中方法获取[][]数组时发生溢出

     public class two
        {
            int[][] _my=new int[0][0];
            public two ()
        {
        }
        static int count=0;
        public static int count;

ountPath(int[][] mat)
    {
        int nextX=0;
        int nextY=0;
        int current=mat[0][0];
        if (current<=9)
        {
            nextX=current;
            nextY=current;
            if (checkBorders(0,0,nextX,nextY,mat)==0)
            {
                return 0;
            }
        }
        else
        {
            nextX=(int)current/10;
            nextY=current%10;
            if (checkBorders(0,0,nextX,nextY,mat)==0)
            {
                return 0;
            }
        }
        countPath(mat,nextX,nextY);
        countPath(mat,nextY,nextX);
        return count;
    }

    public static int countPath(int[][] mat,int x,int y)
    {
        int current=mat[x][y];
        int nextX=0;
        int nextY=0;
        int terminate=0;
        if (current<=9)
        {
            nextX=current;
            nextY=current;
            if (checkBorders(x,y,nextX,nextY,mat)==0)
            {
                return 0;
            }
        }
        else
        {
            nextX=(int)current/10;
            nextY=current%10;
            if (checkBorders(x,y,nextX,nextY,mat)==0)
            {
                return 0;
            }
        }

        if (((mat.length-1)==nextY)&&((mat[0].length-1)==nextX))
        {
           terminate=1;
        }

        if (terminate==1)
            count++;
        else
        {
        countPath(mat,nextX,nextY);
        countPath(mat,nextY,nextX);
        }
        return count;
    }

    public static int checkBorders(int x,int y,int x1,int y1,int[][] mat)
    {
        int maxX=mat[0].length;
        int maxY=mat.length;
        if ((x+x1)>maxX)
            return 0;
        else if ((y+y1)>maxY)
            return 0;
        else return 1;
    }

}

请帮我修复代码。

【问题讨论】:

  • 怎么不工作了? count 是静态变量吗?顺便说一句,在 java 中你可以使用 boolean
  • 如果代码是自包含的,它不仅可以说明问题所在,还可以发布完整的代码。
  • 是的,我使用静态计数变量。

标签: java recursion path


【解决方案1】:

您必须再添加一个 bool 数组,您将在其中存储已访问过的状态。现在您可能会遇到以下情况:

你处于状态 A。 从状态 A 你可以去状态 B 和 C。 从状态 B 你可以转到状态 A

而且记忆会大大提高计算速度。

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-11
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    相关资源
    最近更新 更多