gpt4 book ai didi

java - 如何创建二维数组的克隆?

转载 作者:行者123 更新时间:2023-12-02 06:32:55 24 4
gpt4 key购买 nike

我正在尝试创建 myBoard[][] 的克隆,因为现在当我尝试返回它时,我得到了所有不正确的错误值。

我到底应该在哪里克隆它,以及如何克隆它,以便我可以获得具有合法值而不是全部错误值的 myBoard[][] 的副本?我试图用 public boolean[][] getBoard() 在底部返回它

package model;

public class NQueensModel
{
private int myNumsQueen;
public int myPossibilities=0;
private boolean[][] myBoard;
private boolean[][] myGridBoard;

public static void main (String[] args) {
//...
}
public NQueensModel(int nQueens)
{
myNumsQueen = nQueens;
myPossibilities=0;
myBoard = new boolean[myNumsQueen][myNumsQueen];
}
public boolean solvePuzzle()
{
return solvePuzzle(0);
}
private boolean solvePuzzle(int ncolumn)
{
if(ncolumn>myNumsQueen-1)
{
myPossibilities++;
}
int i;
for( i =0; i<myNumsQueen;i++)
{
if(this.isSafeMove(i, ncolumn)==true)
{
this.placeQueen(i,ncolumn);
if(this.solvePuzzle(ncolumn+1)==true)
{
return true;
}
this.removeQueen(i, ncolumn);
}
}
return false;
}

private boolean doIt(int county)
{
if(county>0)
{
return true;
}
else
{
return false;
}
}

private boolean isSafeMove(int row, int col)
{
if(row <0 || row>=myNumsQueen || col<0 || col>=myNumsQueen)
{
return false;
}
else if(this.checkLowerDiag(row, col)==true ||this.checkUpperDiag(row, col)==true ||this.checkLeft(row,col)==true)
{
return false;
}
else
{
return true;
}
}

private boolean checkUpperDiag(int row, int col)
{
if(row==0)
{
return false;
}
else
{
for(int i=row, j = col; i>=0 && j>=0; i--, j--)
{
if(myBoard[i][j]==true)
{
return true;
}
}
return false;
}
}

private boolean checkLowerDiag(int row, int col)
{
if(col==0 )
{
return false;
}
if(row==myNumsQueen-1){
return false;
}
else
{
for(int i = row, j = col; i<myNumsQueen && j>=0; i++, j--)
{
if(j>=myNumsQueen)
{
return false;
}
else if(myBoard[i][j]==true)
{
return true;
}
}
return false;
}
}

private boolean checkLeft(int row, int col)
{
if(col==0)
{
return false;
}
else
{
for(int i = col; i>=0; i--)
{
if(i>=myNumsQueen)
{
return false;
}

else if(myBoard[row][i]==true)
{
return true;
}
}
return false;
}
}
private boolean placeQueen(int row, int col)
{
if(col>=myNumsQueen)
{
return false;
}

myBoard[row][col] = true;
return true;
}
private boolean removeQueen(int row, int col)
{
myBoard[row][col] = false;
return false;
}
public int getPossibilities(){
return myPossibilities;
}
public boolean[][] getBoard()
{
for(int i = 0; i<5; i++)
{
for(int j = 0; j<5; j++)
{
System.out.println("myBoard : " +myBoard[i][j]);
}
}
return myBoard;
}
}

最佳答案

好吧,如果您只是想创建一个克隆数组,则必须通过迭代旧数组并复制值来构建它:

for (int i = 0; i < oldArray.length; ++i)
for (int j = 0; j < oldArray[0].length; ++j)
newArray[i][j] = oldArray[i][j];

关于java - 如何创建二维数组的克隆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19918249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com