首页 > 解决方案 > 在 8 谜题游戏中获得继任者

问题描述

@Override
public List<List<Integer>> getSuccessors(List<Integer> currentState) {
    List<List<Integer>> successors = new ArrayList<>();
    List<Integer> state = new ArrayList<>();
       int index = 0, temp = 0;
       for(int i = 0; i < 9; i++) {
           state.add(currentState.get(i));
           // copying values into another array
           if(state.get(i) == 0){
               index = i;
               // index where there is space
           }

           /* if possibility to move left */
           if(index != 0 && index != 3 && index != 6){
               // swap i and its left i.e., i-1
               temp = state.get(i);
               state.add(i, state.get(i-1));
               state.add(i-1, temp);

               // add the state to successor
               successors.addAll(Arrays.asList()) ;

               // reswap to go the original state
               temp = state.get(i);
               state.add(i, state.get(i-1));
               state.add(i-1, temp);
           }

           /* check possibility to move right */
           if(index!=2 && index!=5 && index!=8){
               // swap i and its right i.e., i+1
               temp = state.get(i);
               state.add(i, state.get(i+1));
               state.add(i+1, temp);

               // add the state to succesor
               successors.addAll(Arrays.asList()) ;

               // reswap to go the original state
               temp = state.get(i);
               state.add(i, state.get(i+1));
               state.add(i+1, temp);
           }

           /* check possibility to move up */
           if(index!=0 && index!=1 && index!=2){
               // swap i and its up i.e., i-3
               temp = state.get(i);
               state.add(i, state.get(i-3));
               state.add(i-3, temp);

               // add the state to succesor
               successors.addAll(Arrays.asList()) ;

               // reswap to go the original state
               temp = state.get(i);
               state.add(i, state.get(i-3));
               state.add(i-3, temp);
           }

           /* check possibility to move down */
           if(index!=6 && index!=7 && index!=8){
               // swap i and its down i.e., i+3
               temp = state.get(i);
               state.add(i, state.get(i+3));
               state.add(i+3, temp);

               // add the state to succesor
               successors.addAll(Arrays.asList()) ;

               // reswap to go the original state
               temp = state.get(i);
               state.add(i, state.get(i+3));
               state.add(i+3, temp);
           }
       }
       return successors;
}

嗨,所以我对此有点陌生,我一直在努力解决这个问题。给定整数列表的当前状态,它应该返回一组后继。这是一个 8 字谜游戏。我收到 IndexOutOfBoundsException ,但我不知道如何。请帮忙。

顺便说一句,这是我在这里的第一个问题,所以请原谅我的任何新手错误。

标签: java

解决方案


推荐阅读