首页 > 解决方案 > Java 2D 数组硬币收集游戏来自较大的相邻单元

问题描述

我的问题如下:

我有一个大小为 nxm 的二维数组,在一行中输入。在接下来的 n 行中,有 m 个元素填充数组。到目前为止,一切都很好。

场上有一个棋子,总是从场上唯一的 0 开始(假设总是有一个 0)。它可以上下左右移动。它总是移动到硬币最多的相邻单元格,并且每次移动都会收集 1 个硬币(=> 将访问的单元格清空 1)。pawn 这样做直到它周围只有 0 并且它不能再收集任何东西。我需要找到所有收集到的硬币的总和。

这是 Paint 中第一步的表示:

硬币收集第一步:

在此处输入图像描述

样本输入:4 3、3 2 4、2 0 3、1 1 5、2 2 5 -> 输出:22

到目前为止,这是我的代码:我对 targetCell 有一些未完成的工作(我仍然想知道如何在循环中动态获取它的坐标,以便每个具有比前一个值更大的值的单元格变成一个 targetCell。)我也是坚持使用我刚刚创建的方向。任何提示都会对我进一步开发任务有用。

    Scanner scanner = new Scanner(System.in);

    String input = scanner.nextLine();
    String[] my_array = input.split(" ");
    int[] array = Arrays.stream(my_array).mapToInt(Integer::parseInt).toArray();
    int n = array[0]; // rows of matrix
    int m = array[1]; // cols of matrix

    int[][] matrix = new int[n][m];

    for (int i = 0; i < n; i++) {
        String line = scanner.nextLine();
        String[] numbers = line.split(" ");
        matrix[i] = new int[m];
        for (int j = 0; j < m; j++) {
            matrix[i][j] = Integer.parseInt(numbers[j]);
        }
    }

    int startPoint = 0;
    int currentRow = 0;
    int currentCol = 0;

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (matrix[i][j] == 0) {
                startPoint = matrix[i][j];
                currentRow = i;
                currentCol = j;
            }
        }
    }

    int target1 = 0;
    int target2 = 0;
    int targetCell = 0;

            target1 = Math.max(matrix[currentRow - 1][currentCol], matrix[currentRow + 1][currentCol]);
            target2 = Math.max(matrix[currentRow][currentCol - 1], matrix[currentRow][currentCol + 1]);
            targetCell = Math.max(target1, target2);
            System.out.println(targetCell);

            int hDirection = 1;
            if (targetCol < currentCol) {
                hDirection = -1;
            }
            int vDirection = 1;
            if (targetRow < currentRow) {
                vDirection = -1;
            }
        }
    }
}

标签: javaarraysmultidimensional-arraydynamic-arrays

解决方案


(无法发表评论,所以暂时使用答案。抱歉)

我的第一个想法是为运行保留一个全局变量,以便在收集硬币时将其添加到当前值;类似于在俄罗斯方块等游戏中保持得分的方式。那是假设我没看错。

所以像:

private static int current_score = 0; //Assuming no use of objects so using static

无法理解此示例中的示例输入。如果您可以给出最终得分的三轮场景,我可以为您提供更好的见解。


推荐阅读