今天好朋友给我发了一个跳青蛙的智力题:
让左右两边的青蛙交换位置。
要求:
1:用鼠标点青蛙头部,它会向前跳;
2:它最多只能跳过一个青蛙;
3:按红色箭头,游戏复原。
4:此题肯定有解,不要怀疑。
据说年薪50万水准的人三分钟之内就能完成。看来我就是个码农啊,哎!
点不出来不甘心,干脆用代码:
import java.awt.Point;
import java.util.Stack;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// 栈processes中存储结果
Stack processes = new Stack();
// 初始化
processes.push(new StringBuffer("AAA_BBB"));
getSolutions(processes);
}
/**
* 找出解决方案
*/
static boolean getSolutions(Stack stack) {
StringBuffer strBuffer = new StringBuffer(stack.lastElement());
// 如果此时strBuffer等于"BBB_AAA",表明成功,返回true
if (strBuffer.toString().equals("BBB_AAA")) {
int i;
for (i = 0; i < stack.size() - 1; i++)
System.out.print(stack.get(i) + " → ");
System.out.println(stack.get(i));
return true;
}
// 根据strBuffer找出可以的交换,并存储在points中
Stack points = new Stack();
int index = strBuffer.indexOf("_");
for (int i = index - 2; i <= index + 2; i++) {
if (i == index || i < 0 || i > 6)
continue;
if (i < index && strBuffer.charAt(i) == 'A' || i > index
&& strBuffer.charAt(i) == 'B') {
points.add(new Point(i, index));
}
}
// 当前没有可用的变换,返回false
if (points.isEmpty())
return false;
// 依次尝试
for (int i = 0; i < points.size(); i++) {
Point onePoint = points.get(i);
swapChar(strBuffer, onePoint.x, onePoint.y);
stack.push(strBuffer);
getSolutions(stack);
// 恢复交换,并stack移除栈顶元素
swapChar(strBuffer, onePoint.y, onePoint.x);
stack.pop();
}
return false;
}
/**
* 交换strBuffer中的两个字符
*/
static void swapChar(StringBuffer strBuffer, int left, int right) {
// 交换
char tmp = strBuffer.charAt(left);
strBuffer.setCharAt(left, strBuffer.charAt(right));
strBuffer.setCharAt(right, tmp);
}
}
输出结果如下:
AAA_BBB → AA_ABBB → AABA_BB → AABAB_B → AAB_BAB → A_BABAB → _ABABAB → BA_ABAB → BABA_AB → BABABA_ → BABAB_A → BAB_BAA → B_BABAA → BB_ABAA → BBBA_AA → BBB_AAA
AAA_BBB → AAAB_BB → AA_BABB → A_ABABB → ABA_ABB → ABABA_B → ABABAB_ → ABAB_BA → AB_BABA → _BABABA → B_ABABA → BBA_ABA → BBABA_A → BBAB_AA → BB_BAAA → BBB_AAA