gpt4 book ai didi

java - 从某个元素开始在二维数组中搜索java

转载 作者:行者123 更新时间:2023-12-01 10:00:17 25 4
gpt4 key购买 nike

我正在尝试编写一个代码来搜索二维数组,并尝试找到最接近“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 <= row < numOfRows0 <= 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");
}

关于java - 从某个元素开始在二维数组中搜索java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36863997/

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