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