public static enum Action {
No, LToM, MToL, MToR, RToM
}
public static int hanoiProblem2(int num, String left, String mid, String right) {
Stack<Integer> lS = new Stack<Integer>();
Stack<Integer> mS = new Stack<Integer>();
Stack<Integer> rS = new Stack<Integer>();
lS.push(Integer.MAX_VALUE);
mS.push(Integer.MAX_VALUE);
rS.push(Integer.MAX_VALUE);
for (int i = num; i > 0; i--) {
lS.push(i);
}
Action[] record = { Action.No };
int step = 0;
while (rS.size() != num + 1) {
step += fStackTotStack(record, Action.MToL, Action.LToM, lS, mS, left, mid);
step += fStackTotStack(record, Action.LToM, Action.MToL, mS, lS, mid, left);
step += fStackTotStack(record, Action.RToM, Action.MToR, mS, rS, mid, right);
step += fStackTotStack(record, Action.MToR, Action.RToM, rS, mS, right, mid);
}
return step;
}
public static int fStackTotStack(Action[] record, Action preNoAct,
Action nowAct, Stack<Integer> fStack, Stack<Integer> tStack,
String from, String to) {
if (record[0] != preNoAct && fStack.peek() < tStack.peek()) {
tStack.push(fStack.pop());
System.out.println("Move " + tStack.peek() + " from " + from + " to " + to);
record[0] = nowAct;
return 1;
}
return 0;
}
public static void main(String[] args) {
int num = 4;
// solution 2
int steps2 = hanoiProblem2(num, "left", "mid", "right");
System.out.println("It will move " + steps2 + " steps.");
System.out.println("===================================");
}
하노이 타워를 푸는 코드입니다. 3 개의 스택을 사용하여 3 개의 타워를 시뮬레이션합니다. 제 질문은 왜 그것은 레코드 변수를 배열로 정의합니까? 작업 [] record = {Action.No}; record [0] = nowAct;스택을 사용하여 하노이 타워 해결하기 (자바)
으로 변경하려고했습니다. 액션 레코드 = 액션입니다. 아니요. record = nowAct; 코드를 실행하지 못했습니다.
이유를 모르겠습니다. 누군가가 그 이유를 설명 할 수 있다면 정말 고맙습니다. 감사합니다. .
은 : 한 번에 왼쪽에서 오른쪽으로 또는 오른쪽에서 왼쪽에서 디스크를 이동할 수 없습니다. 가운데에서 왼쪽으로 오른쪽에서 오른쪽으로 또는 왼쪽에서 오른쪽으로 두어야합니다. –
'{Action.No}'는 하나의 요소를 포함하는 배열이고, Action []을 입력합니다. 그것은'Action.No'와 같지 않습니다.'Action'을 입력하십시오. –
레코드 [0] 만 사용했다는 의미입니다. 배열에서 변수에 '레코드'를 변경할 수 있습니까? 고맙습니다. –