在不更改原始arrayState的情况下将不同的arrayStates添加到ArrayList

时间:2018-10-03 13:57:15

标签: java arrays

我目前正在尝试用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]

1 个答案:

答案 0 :(得分:0)

您需要在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;
}