首页 > 解决方案 > 将不同的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]

标签: javaarrays

解决方案


您需要GameStateswap方法中创建一个新方法,例如:

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;
}

推荐阅读