-1

在 8 字谜题中,当它在棋盘中找到空白棋子(用 0 表示)时,它需要获得所有相邻棋子,一步可以到达。

由于我在实现中将二维板映射到一维数组,因此index()在我的代码中使用它确实有意义。

我想不出一种优雅的方式来实现neighbors()现在,因此它现在涉及相当多的冗余代码。

public class Board {

private char[] tiles;
private int N;

private Board(char[] blocks) {
    N = (int) Math.sqrt(blocks.length);
    this.tiles = new char[blocks.length];
    System.arraycopy(blocks, 0, this.tiles, 0, N * N);
}

private void exch(int i, int j) {
    char swap = tiles[i];
    tiles[i] = tiles[j];
    tiles[j] = swap;
}

public Iterable<Board> neighbors()
{
    Stack<Board> neighbors = new Stack<>();
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            if (tiles[index(i, j)] == 0) {
                Board neighbor;
                if (i > 0) {
                    neighbor = new Board(tiles);
                    neighbor.exch(index(i, j), index(i - 1, j));
                    neighbors.push(neighbor);
                }

                if (j > 0) {
                    neighbor = new Board(tiles);
                    neighbor.exch(index(i, j), index(i, j - 1));
                    neighbors.push(neighbor);
                }

                if (i < N - 1) {
                    neighbor = new Board(tiles);
                    neighbor.exch(index(i, j), index(i + 1, j));
                    neighbors.push(neighbor);
                }

                if (j < N - 1) {
                    neighbor = new Board(tiles);
                    neighbor.exch(index(i, j), index(i, j + 1));
                    neighbors.push(neighbor);
                }
                break;
            }
        }
    }
    return neighbors;
}
}
4

1 回答 1

0
public Stack<Board> update (int check, int checkB, int i, int, j, int index, int indexB, Stack<Board> neighbors, char[] tiles){
   if (check > checkB) {
   neighbor = new Board(tiles);
   neighbor.exch(index(i, j), index(i + index, j + indexB));
   neighbors.push(neighbor);
   }
   return neighbors;
}

像这样调用它,每个条件 4 次 :)

neighbor  = update (i, 0, i, j, -1, 0, neighbor, tiles )

相当于:

if (i > 0) {
    neighbor = new Board(tiles);
    neighbor.exch(index(i, j), index(i - 1, j));
    neighbors.push(neighbor);
}

如果你想减少函数中的变量,你也可以这样做:

public Stack<Board> update (boolean check, int i, int, j, int index, int indexB, Stack<Board> neighbor, char[] tiles){
   if (check) {

然后只需将条件放入通话中

neighbor  = update ((i > 0), i, j, -1, 0, neighbor, tiles )
于 2016-03-03T06:01:59.147 回答