在8难题游戏中获得接班人

时间:2018-11-07 05:07:20

标签: java

@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,但我不知道如何。请帮忙。

顺便说一句,这是我在这里的第一个问题,因此,请问任何菜鸟错误都对不起。

0 个答案:

没有答案