gpt4 book ai didi

java - 访问矩阵中特定单元格的对角线

转载 作者:太空宇宙 更新时间:2023-11-04 09:43:52 26 4
gpt4 key购买 nike

解决 8 个皇后的问题,我实际上陷入了如何访问特定单元格的对角线以在放置皇后时将其设置为 1 的问题。对于必须放置皇后的所选单元格的垂直或水平单元格,有简单的逻辑。

这是我的函数代码,用于将皇后的单元格设置为 1,以便皇后可以攻击。

static int[][] SetPos(int csp[][],int row,int col){
int count = 0, n = csp.length;
for (int i = 0; i < csp.length; i++) {
for (int j = 0; j < csp.length; j++) {
if(i==row || j==col){
csp[i][j]=1;
}

if(row==col && i==j){
//csp[row][col]=1;
csp[i][j]=1;
}
if(row+count==i && col+count==j){
csp[i][j]=1;
}

}
count++;
}

return csp;
}

如何改善这种情况:

if(row+count==i && col+count==j){
csp[i][j]=1;
}

这样我就可以得到单元格(5,5)的结果:

 1  0  0  0  0  1  0  0 
0 1 0 0 0 1 0 0
0 0 1 0 0 1 0 0
0 0 0 1 0 1 0 1
0 0 0 0 1 1 1 0
1 1 1 1 1 1 1 1
0 0 0 0 1 1 1 0
0 0 0 1 0 1 0 1

不是这样的:

 1  0  0  0  0  1  0  0 
0 1 0 0 0 1 0 0
0 0 1 0 0 1 0 0
0 0 0 1 0 1 0 0
0 0 0 0 1 1 0 0
1 1 1 1 1 1 1 1
0 0 0 0 0 1 1 0
0 0 0 0 0 1 0 1

回溯不是现在的问题。

最佳答案

你的情况

  if(row==col && i==j){
//csp[row][col]=1;
csp[i][j]=1;
}

仅当 row==col 时才有效。否则你只会得到水平和垂直的数字。

如果您想标记从行和列开始的对角线,此代码应该可以工作:

  if(i-j==row-col){ //diagonal up_left to down_right
csp[i][j]=1;
}

if(i+j==row+col) { //diagonal down_left to up_right
csp[i][j]=1;
}

关于java - 访问矩阵中特定单元格的对角线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55655444/

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