本文共 2195 字,大约阅读时间需要 7 分钟。
广度优先搜索(Breadth-first Search)算法描述:
int volume = 0;int oil = 0;
switch (n) {case 1: // 瓶子1向瓶子2倒油 if (!bottle1.isEmpty() && !bottle2.isFull()) { n = bottle2.needForFull() <= bottle1.oil ? bottle2 .needForFull() : bottle1.oil; newState = new StateNode(bottle1.oil - n, bottle2.oil + n, bottle3.oil, this); } break;case 2: // 瓶子1向瓶子3倒油 if (!bottle1.isEmpty() && !bottle3.isFull()) { n = bottle3.needForFull() <= bottle1.oil ? bottle3 .needForFull() : bottle1.oil; newState = new StateNode(bottle1.oil - n, bottle2.oil, bottle3.oil + n, this); } break;case 3: // 瓶子2向瓶子1倒油 if (!bottle2.isEmpty() && !bottle1.isFull()) { n = bottle1.needForFull() <= bottle2.oil ? bottle1 .needForFull() : bottle2.oil; newState = new StateNode(bottle1.oil + n, bottle2.oil - n, bottle3.oil, this); } break;case 4: // 瓶子2向瓶子3倒油 if (!bottle2.isEmpty() && !bottle3.isFull()) { n = bottle3.needForFull() <= bottle2.oil ? bottle3 .needForFull() : bottle2.oil; newState = new StateNode(bottle1.oil, bottle2.oil - n, bottle3.oil + n, this); } break;case 5: // 瓶子3向瓶子1倒油 if (!bottle3.isEmpty() && !bottle1.isFull()) { n = bottle1.needForFull() <= bottle3.oil ? bottle1 .needForFull() : bottle3.oil; newState = new StateNode(bottle1.oil + n, bottle2.oil, bottle3.oil - n, this); } break;case 6: // 瓶子3向瓶子1倒油 if (!bottle3.isEmpty() && !bottle2.isFull()) { n = bottle2.needForFull() <= bottle3.oil ? bottle2 .needForFull() : bottle3.oil; newState = new StateNode(bottle1.oil, bottle2.oil + n, bottle3.oil - n, this); } break;}
ArrayListstateList = new ArrayList (); // 存放所有出现过的状态的数组
if (!tag) { // 如没出现过 加入状态队列和数组 stateQueue.addFirst(newState); stateList.add(newState);}
转载地址:http://ovwob.baihongyu.com/