【问题标题】:What would I be returning in this recursive method?我会在这个递归方法中返回什么?
【发布时间】:2021-05-12 06:32:07
【问题描述】:
public static int bombs(char[][] maze, int row, int col, ArrayList<int[]> checked, int bombs)
    {
        int size = maze.length;
        String value = Character.toString(maze[row][col]);
        if (value.equals("#"))//add one to bomb if it went through a wall
        {
            bombs = bombs+1;
        }
        if(row==size-1&&col==size-1)//if it has reached the end
        {
            return steps;
        }
        if(inBounds(row,col,size)) //if point is in bounds
        {
            if(!pointWasChecked(row,col,checked)) 
            {       //if point has not been checked
                checked.add(new int[]{row, col});
                
            }
        }
        return 0;
    }
/*
. . # # #
. # . . #
# # # # #
# . # . .
# # # . .
example maze, this one's smallest path should be 2 bombs used
. is a path
# is a wall
/*

这是一种遍历迷宫的递归方法,它在到达墙壁时使用炸弹,但我想返回所需的最小数量的炸弹。我已经知道如何通过再次调用该方法并执行 row+1、row-1、col+1、col-1 来遍历迷宫。我只是对我需要返回什么感到困惑,这样我才能走到最后,不要最终返回零,并返回最少数量的炸弹。 感谢您的帮助!

【问题讨论】:

  • 递归方法是一种通过调用自身来获取结果的方法。您在上面发布的内容看起来并不像使用递归。

标签: java recursion maze


【解决方案1】:

短版:返回 Integer.MAX_VALUE 而不是零。

长版:假设return steps 实际上是return bombs,并且您已经知道如何进行递归调用:

如果当前位置有效(入站、尚未检查且未结束),您将在所有 4 个方向进行探索。 在探索完所有四个方向后,您最终会得到 4 个值(每个方向后的步数)。然后返回每个值中的最小值。

如果当前位置无效,则必须返回一个大于任何正确值的值。最好的选择是Integer.MAX_VALUE,这是可以编码为整数的最大值。

请注意,蛮力递归在大型迷宫中可能需要相当长的时间,并且很容易导致堆栈溢出。

【讨论】:

    猜你喜欢
    • 2020-10-22
    • 2019-06-26
    • 2022-01-17
    • 2022-11-10
    • 2013-10-14
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多