In an 8-puzzle, when it finds the blank tile (which is represented by 0) in the board, it needs to get all neighboring boards that can be reached in one move.
As I have mapped a 2-dimensional board to a 1-dimensional array in my implementation, it does make sense to use index()
in my code.
I can not figure out an elegant way to implement the neighbors()
now so that it involved quite a bit of redundant code now.
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;
}
}