-1
在8謎題中,當它找到板子中的空白瓷磚(用0表示)時,它需要一次移動可以到達的所有相鄰板子。如何簡化在8拼圖中移動拼貼的代碼?
因爲我在我的實現中將二維板映射到一維數組,所以在我的代碼中使用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;
}
}
這似乎是可能更適合於[代碼審查SE(http://codereview.stackexchange.com/)網絡的一個問題? –
我投票結束這個問題,因爲它是一個代碼審查的請求。 – Raedwald