Java 在二维数组中搜索。
我有一种方法,可以确定给定行和列的棋盘上的正方形是否受到第1列到第1列中任何皇后的攻击。但是我在板[row-column+y][y]==QUEENJava 在二维数组中搜索。,java,Java,我有一种方法,可以确定给定行和列的棋盘上的正方形是否受到第1列到第1列中任何皇后的攻击。但是我在板[row-column+y][y]==QUEEN private boolean isUnderAttack(int row, int column) { for (int y=0; y<column; y++) { if (board[row][y] == QUEEN || // possible hor
private boolean isUnderAttack(int row, int column)
{
for (int y=0; y<column; y++)
{
if (board[row][y] == QUEEN || // possible horizontal attack
board[row-column+y][y] == QUEEN || // diagonal NW
board[row+column-y][y] == QUEEN) // diagonal SW
return true;
}
return false;
}
private boolean isUnderAttack(int行,int列)
{
对于(int y=0;yPay attation to:
row + column - y
此操作可以返回小于0的数字
你的班级应该是这样的:
import java.util.Arrays;
public class Board {
private final int[][] board;
private final int dimention;
public static void main(final String[] args) {
final Board p = new Board(6);
for (final int[] i : p.board) {
System.out.println(Arrays.toString(i));
}
p.isUnderAttack(2, 3);
System.out.println("\n\n");
for (final int[] i : p.board) {
System.out.println(Arrays.toString(i));
}
}
public Board(final int dimention) {
this.dimention = dimention;
this.board = new int[dimention][dimention];
}
private void isUnderAttack(final int row, final int column) {
for (int y = 0; y < this.dimention; y++) {
this.board[y][row] = 1; // possible horizontal attack
this.board[column][y] = 2; // possible vertical attack
}
int staringRow = column - row;
int y = 0;
do {
this.board[staringRow][y] = 3; // diagonal SW
} while ((++staringRow < this.dimention) && (++y < this.dimention));
int staringCol = column + row;
int x = 0;
do {
this.board[x][staringCol] = 4; // diagonal NW
} while ((++x < this.dimention) && (--staringCol < this.dimention));
}
}
什么例外?ArrayIndexOutOfBounds?您应该提供更多信息,但问题是(很可能是)非常清楚。从异常中的索引,你应该能够找到它。在NW测试中,如果所讨论的正方形具有低行、低y和高列值,你将得到负索引。谢谢…不是我想要的。但是给了我一个想法
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]
[0, 0, 1, 0, 0, 4]
[3, 0, 1, 0, 4, 0]
[0, 3, 1, 4, 0, 0]
[2, 2, 4, 2, 2, 2]
[0, 4, 1, 3, 0, 0]
[4, 0, 1, 0, 3, 0]