java - 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;
}
}
}
}
解决方案
(无法发表评论,所以暂时使用答案。抱歉)
我的第一个想法是为运行保留一个全局变量,以便在收集硬币时将其添加到当前值;类似于在俄罗斯方块等游戏中保持得分的方式。那是假设我没看错。
所以像:
private static int current_score = 0; //Assuming no use of objects so using static
无法理解此示例中的示例输入。如果您可以给出最终得分的三轮场景,我可以为您提供更好的见解。
推荐阅读
- docker - 无法启动容器:OCI 运行时创建失败:container_linux.go:349
- sql-server - SQL Server - 使用 html 格式将 nvarchar 变量添加到电子邮件
- java - 你如何为android中的特定单词设置粗体样式?
- gcc - Gcc Makefile .elf 文件失败
- java - 如何在android studio的textview中显示recyclerview的总数
- php - 循环遍历多维 PHP 数组的次数太多了
- asp.net - 从外部 URL 重定向回 ASP.NET MVC 中的操作方法后无法保留 cookie
- python - 如何在 Matplotlib 中的 Y 轴和开始和结束垂直条之间留出一些空间
- c++ - 在opencv中获取C ++中灰度图像的直方图
- sql - MS Sql 按子字符串拆分特定列