為我的 AI 類編寫(xiě)一段代碼,旨在列出給定三個(gè)水壺問(wèn)題的所有可能狀態(tài)(您可以裝滿任何水壺,或?qū)⒈M可能多的水倒入另一個(gè)水壺,或清空任何水壺,如您可以按任意順序多次)從空罐子開(kāi)始。由于某種原因,在記錄了 88 個(gè)看似不同的狀態(tài)后,第 89 個(gè)與第一個(gè)相同,我最終用完了空間,因?yàn)樗h(huán)了。我認(rèn)為這與我如何檢查狀態(tài)是否不同有關(guān),但無(wú)法弄清楚。任何幫助將不勝感激。import java.util.ArrayList; import java.util.List;public class AI { private static final int[] start=new int[]{0,0,0}; private static int[] jugs; public static void main(String[] args){ jugs=new int[]{Integer.parseInt(args[0]), Integer.parseInt(args[1]),Integer.parseInt(args[2])}; String out=""; out=out.concat("{"); for (int[] state:addStates(start,new ArrayList<>())) { out=out.concat("{"+state[0]+","+state[1]+","+state[2]+"}"); } out=out.substring(0,out.length()-2).concat("}"); System.out.println(out);}private static List<int[]> addStates(int[] start, List<int[]> states) { states.add(start); int[][] newStates={ fillA(start), fillB(start), fillC(start), emptyA(start), emptyB(start), emptyC(start), pour(start,0,1), pour(start,0,2), pour(start,1,0), pour(start,1,2), pour(start,2,0), pour(start,2,1) }; for (int[] child:newStates) { if (!has(states,child)) { states.addAll(addStates(child,states)); } } System.out.println("close"); return states;}private static boolean has(List<int[]> list, int[] e) { //finds out if list contains something with the same values as e for (int[] el:list) { boolean is=true; for(int i=0;i<e.length;i++){ if (el[i]!=e[i]){ is=false; } } if(is){ return true; } } return false;}
1 回答

aluckdog
TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超7個(gè)贊
問(wèn)題是我同時(shí)使用了states.add(start)
and states.addAll(addStates(child,states))
,這意味著我多次添加了每個(gè)元素。修復(fù)此問(wèn)題后,代碼運(yùn)行良好。
添加回答
舉報(bào)
0/150
提交
取消