我的以下代码出现问题:
public class Board {
private int[][] blocks;
private int dim;
private int hDistance;
private int mDistance;
private int indexRow;//row of the empty block;
private int indexColumn;//column of the empty block;
public Board(int[][] blocks)
{
dim = blocks.length;
this.blocks = new int[dim][dim];
this.blocks = blocks;
mDistance = manhattan();
hDistance = hamming();
}
public Board twin()
{
Board twinBoard = this;
if(indexRow!=0)
{
exch(twinBoard.blocks, 0, 0, 0, 1);//swap(twinBoard.blocks[0][0] with twinBoard.blocks[0][1]
}
else
{
exch(twinBoard.blocks, 1, 0, 1, 1);//swap(twinBoard.blocks[1][0] with twinBoard.blocks[1][1]
}
return twinBoard;
}
private void exch(int[][] blocks, int i1, int j1, int i2, int j2)
{
int temp;
temp = blocks[i1][j1];
blocks[i1][j1] = blocks[i2][j2];
blocks[i2][j2] = temp;
}
public static void main(String[] args)
{
int[][] a = {
{2,0,4},
{1,5,7},
{3,6,8}
};
Board board1 = new Board(a);
Board board2 = board1.twin();
}
}
打印出board1.blocks
我得到了:
2,0,4
5,1,7
-3,6,8-
而不是
2,0,4
-1,5,7-
-3,6,8-
board1.blocks
是如何交换的?我怎样才能board2.block
交换,board1.block
保持不变?
答案 0 :(得分:0)
问题在于这一行:
Board twinBoard = this;
您的代码的“双胞胎”是不不同的主板:它与this
是同一个主板,因此对twinBoard
所做的任何更改都会反映在{{1}同样。
要解决此问题,请定义用于复制电路板的新构造函数:
this
在此构造函数中,您需要复制private Board(Board other) {
...
}
,并将board
,hDistance
和其他字段设置为mDistance
板中的值。现在你可以使用这个构造函数来制作一块双板:
other