java - 我在尝试用 int 值填充堆栈数组时遇到 OutOfMemoryError
问题描述
我一直在使用堆栈研究 hanoi 递归塔,但我得到了 OutOfMemoryError: Java heap space in the hanoi function
import java.util.Scanner;
import java.util.Stack;
public class Hanoi {
public static Stack<Integer>[] towersOfHanoi = new Stack[4];
public static int moves;
public static void hanoi(int n) {
for(int i = 0; i <= 3; i++) {
towersOfHanoi[i] = new Stack<Integer>();
}
for(int i = n; n > 0; i--) {
towersOfHanoi[1].push(i);
}
moveDisc(n, 1, 2, 3);
}
public static void moveDisc(int n, int peg1, int peg2, int peg3) {
moveDisc(n-1, peg1, peg2, peg3);
int i = towersOfHanoi[peg1].pop();
towersOfHanoi[peg2].push(i);
moves++;
moveDisc(n-1, peg3, peg1, peg2);
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
towersOfHanoi[1] = new Stack<Integer>();
towersOfHanoi[2] = new Stack<Integer>();
towersOfHanoi[3] = new Stack<Integer>();
System.out.println("Enter number of discs: ");
int n = in.nextInt();
in.close();
hanoi(n);
System.out.println(moves);
}
}
解决方案
问题出在 hanoi 函数中的第二个 for 循环中
for(int i = n; n > 0; i--) {
towersOfHanoi[1].push(i);
}
应该
for(int i = n; i > 0; i--) {
towersOfHanoi[1].push(i);
}
在您将其设置为“n> 0”之前,但 n 永远不会改变。你希望它是 'i>0'
我还应该提到,您可能会在 moveDisk 方法中获得无限递归。你应该做一个基本案例。但是,这将解决您在 hanoi 函数中遇到的 OOM 错误
推荐阅读
- c++ - 存储为 RTC_NOINIT_ATTR (ESP32) 时的 C++ int 未定义行为
- c# - c# 取消powershell/MFA登录窗口优雅地运行管道
- php - 当我运行程序时,NetBeans 显示“等待连接 netbeans-xdebug”
- java - 如何在 Micronaut 中使用使用 Spring 编写的 SDK
- macos - Homebrew 如何编译源代码?有日志吗?
- python - For-loop 不起作用,只打印范围内的第一个数字
- javascript - R传单中的饼图,将计数变为总和并控制更多大小
- typescript - 参数值应确定其他参数键
- node.js - AWS DynamoDB putItem 如果值存在于另一个项目的 pk 中
- r - 将 YYYYMMDDHHMMSS 转换为 r 中的日期和时间类