java - 将不同的arrayStates添加到ArrayList而不改变原始arrayState
问题描述
我目前正在尝试在 java 中解决 2d 滑块益智游戏。我想使用 BFS 解决这个难题,但是每当我向树中添加顶点时,父节点都会发生变化,并且所有相邻的顶点都是相同的。让我展示一些代码来解释我的意思。
这是我的 GameState 对象,它代表树中的每个节点。
public class GameState {
public int[][] state; //state of the puzzle
public GameState parent; //parent in the game tree
public GameState(int[][] state, GameState parent) {
//initialize this.state to state, this.parent to parent
this.state = new int[3][3];
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++) {
this.state[i][j] = state[i][j];
}
}
this.parent = parent;
}
这是我获取所有可能的相邻顶点的方法。
public ArrayList<GameState> getAdjacent() {
//Use the swap functions to generate the new vertices of the tree
//Beware of the boundary conditions, i.e. don’t swap left when you are
//already on the left edge
ArrayList<GameState> vertices = new ArrayList<>();
int row = 0;
int col = 0;
//Gets my zero int index
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++) {
if(this.state[i][j] == 0){
row = i;
col = j;
}
}
}
//Checking if we can swap up
if(row != 0) {
vertices.add(swapUp(this, row, col));
}
//Checking if we can swap down
if(row != 2) {
vertices.add(swapDown(this, row, col));
}
//Checking if we can swap left
if(col != 0) {
vertices.add(swapLeft(this, row, col));
}
//Checking if we can swap right
if(col != 2) {
vertices.add(swapRight(this, row, col));
}
return vertices;
}
最后,例如,这是调用 swapUp 时发生的情况。
public GameState swapUp(GameState s, int row, int col) {
s.parent = s;
int temp = state[row][col]; // Mark zero as temp
s.state[row][col] = s.state[row-1][col];
s.state[row-1][col] = temp;
return s;
}
我需要添加到 arrayList 的每个游戏状态都不同,但是当我测试程序时,这就是添加到列表中的顶点所输出的内容。
[1, 5, 0]
[3, 7, 4]
[6, 8, 2]
1
[1, 5, 0]
[3, 7, 4]
[6, 8, 2]
2
[1, 5, 0]
[3, 7, 4]
[6, 8, 2]
解决方案
您需要GameState
在swap
方法中创建一个新方法,例如:
public GameState swapUp(int row, int col) {
GameState s = new GameState(state, this);
// no need for swap, (row,col) is 0, (row-1,col) becomes 0
s.state[row][col] = s.state[row-1][col];
s.state[row-1][col] = 0;
return s;
}
推荐阅读
- angular - 如何使用单个服务人员安装多语言 Angular PWA?
- javascript - 为什么反应上下文提供程序组件呈现两次
- ms-access - 用于访问直通查询的雪花的 ODBC 连接字符串
- ios - 我可以检测用户是否点击了蓝色状态栏来打开应用程序?
- firebase - 在 Firestore 中按文档名称获取数据
- jekyll - 从 Jekyll 子文件夹中的 _posts 生成页面
- c# - 当构造线程同时进行写入和读取时,是否可以从另一个线程观察部分构造的对象?
- javascript - 使用自定义开关上的选中属性启用表单字段
- authentication - 无法在 NGINX 中删除用户身份验证
- javascript - :host-context 在 Lit-Element Web 组件中未按预期工作