java - 在 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 ,但我不知道如何。请帮忙。
顺便说一句,这是我在这里的第一个问题,所以请原谅我的任何新手错误。
解决方案
推荐阅读
- mysql - Query showing when a rental is overdue?
- mysql - MySQL:授权中未显示 REQUIRE SSL
- php - session_start():解码会话对象失败
- python - Single row Points to Linestring
- excel - 删除重复项同时忽略 VBA 中的空白单元格
- bootstrap-4 - 在控制列数的同时实现引导卡的动态宽度和高度相等
- php - 如何在 Azure 上启用 PUT 和 DELETE 请求?
- angular - 无法使用 moment 调用类型缺少调用签名的表达式
- django - 尝试在 pythonanywhere 上部署但不工作
- java - How to count the number of external tags only (XML)?