33,006
社区成员
发帖
与我相关
我的任务
分享
import java.util.LinkedList;
public class lastStand {
private int stepNum = 5;
private boolean[] allStep;
public lastStand() {
}
public static void main(String[] args) {
lastStand anInstance = new lastStand();
anInstance.play();
}
private void play() {
allStep = new boolean[findIndex(stepNum-1, stepNum-1)+1];
boolean result = false;
for (int i = 0; i < stepNum; i++) {
result = takeStep(i, true);
if (result == true)
break;
}
if (result == true)
System.out.println("P1 Win");
else
System.out.println("P2 Win");
}
private void makeMove(int a, int b) {
allStep[findIndex(a, b)] = true;
}
private void unMakeMove(int a, int b) {
allStep[findIndex(a, b)] = false;
}
private int findIndex(int a, int b) {
if (a >= b)
return a * (a + 1) / 2 + b;
else
return b * (b + 1) / 2 + a;
}
private LinkedList<int[]> findStep(int lastStep) {
LinkedList<int[]> stepList = new LinkedList<int[]>();
for (int i = 0; i < stepNum; i++) {
if (!allStep[findIndex(lastStep, i)]) {
int step[] = new int[] { lastStep, i };
stepList.add(step);
}
}
return stepList;
}
private boolean takeStep(int lastStep, boolean side) {
LinkedList<int[]> stepList = findStep(lastStep);
if (stepList.isEmpty()) {
if (side)
return false;
else
return true;
} else {
boolean result = false;
while (!stepList.isEmpty()) {
int[] step = stepList.pop();
makeMove(step[0], step[1]);
result = takeStep(step[1], !side);
if (side) {
if (result == true) {
unMakeMove(step[0], step[1]);
return result;
}
} else {
if (result == false) {
unMakeMove(step[0], step[1]);
return result;
}
}
unMakeMove(step[0], step[1]);
}
return result;
}
}
}