我正在尝试编写一个搜索二维数组的代码,并试图找到最接近“x”的元素,如果“x”中有任何数据,则该元素的坐标是从另一个方法给出的。 。例如,“x”是(3,2)。如果没有空元素,那么代码必须继续搜索整个数组。
public void find(int row, int column) {
for (int i = row - 1; i < row + 2; i++) {
for (int k = column - 1; k < column + 2; k++) {
if (this.arr[i][k].equals(" ")) {
System.out.println(i + "," + k + " is empty.");
return;
}
}
}
}
我正在寻找有关如何编写此方法的任何有用建议的前言。 谢谢。
答案 0 :(得分:1)
在假设下
0 <= row < numOfRows
和0 <= column < numOfColumns
此代码将以您所描述的方式搜索指定元素周围的二维数组。 请注意,这不是围绕指定元素的时钟方向圆搜索,而是从左上角到右下角(从上到下,从左到右)搜索
public void find(int row, int column) {
int distance = 1;
int numOfRows = arr.length;
int numOfColumns = 0;
if (arr.length > 0) {
numOfColumns = arr[0].length;
}
int maxDistance = Math.max(numOfRows, numOfColumns);
for (distance = 1; distance < maxDistance; distance ++) {
for (int i = Math.max(row - distance, 0); i <= Math.min(row + distance, numOfRows - 1); i++) {
if (Math.abs(i - row) == distance) {
// Check row
for (int k = Math.max(column - distance, 0); k <= Math.min(column + distance, numOfColumns - 1); k++) {
if (arr[i][k] == null || arr[i][k].trim().isEmpty()) {
System.out.println((i+1) + "," + (k+1) + " is empty.");
return;
} else {
System.out.println((i+1) + "," + (k+1) + " is not empty.");
}
}
} else {
// Check only edge elements
int k = column - distance;
if (k >= 0) {
if (arr[i][k] == null || arr[i][k].trim().isEmpty()) {
System.out.println((i+1) + "," + (k+1) + " is empty.");
return;
} else {
System.out.println((i+1) + "," + (k+1) + " is not empty.");
}
}
k = column + distance;
if (k < numOfColumns) {
if (arr[i][k] == null || arr[i][k].trim().isEmpty()) {
System.out.println((i+1) + "," + (k+1) + " is empty.");
return;
} else {
System.out.println((i+1) + "," + (k+1) + " is not empty.");
}
}
}
}
}
System.out.println("No empty elements");
}