到目前为止,我为这个方法编写的代码是:
int rowCount = 0;
int columnCount = 0;
Pair p = new Pair(0, 0);
public Pair search2D(int[][] data, int element) {
if(data[rowCount].length==columnCount)
{
rowCount++;
columnCount=0;
}
if(data.length > rowCount)
{
if(data[rowCount][columnCount] == element)
{
p = new Pair(rowCount, columnCount);
}
else
{
columnCount++;
search2D(data, element);
}
}
return p;
}"Pair“是我写的一个类,因为Java只允许我返回一个数字,而我试图返回保存元素位置的索引。
在我的main方法中,我有
int[][] table = new int[][] { {3, 2, 8}, {3, 5, 6} };
System.out.println(r.search2D(table, 5));
System.out.println(r.search2D(table, 8));但是,这两个输出都是(1,1)。有人告诉我不要使用任何循环,有人能给我指出正确的方向或告诉我问题在哪里吗?
发布于 2016-03-22 02:37:43
在找到r.search2D(table, 5)之后,您不会重置rowcount和columncount的值。因此,对于r.search2D(table, 8),您得到的答案也是1,1。
要解决此问题,请将函数修改为:
public Pair search2D(int[][] data, int element, int rowcount, int columncount){}并以search2D(data,element,0,0);的身份调用
发布于 2016-03-22 02:38:03
这里有一个我认为应该能解决问题的版本。通常,更好的设计是不依赖全局变量。
public Pair search2D(int[][] data, int element) {
return search2D(0, 0, data, element);
}
public Pair search2D(int i, int j, int[][] data, int element) {
if (i == data.length) {
return new Pair(-1, -1);
}
if (j == data[i].length) {
return search2D(i + 1, 0, data, element);
}
if (data[i][j] == element) {
return new Pair(i, j);
}
return search2D(i, j + 1, data, element);
}我现在知道这可能不是你需要的帮助。你需要帮助来让你的代码正常工作。但是使用它作为替代实现,它展示了递归的一些功能。:)
发布于 2016-03-22 02:38:15
我没有考虑它的递归部分,但是rowCount和columnCount在第一次搜索后不会被重置,你应该改变你的方法,使它们在一开始都是0。
public Pair search2D(int[][] data, int element) {
return search2D(data, element, 0, 0);
}
public Pair search2D(int[][] data, int element, int rowCount, int columnCount) {
//your method
}而且,没有递归的方法可能会更容易。
public Pair search2D(int[][] data, int element) {
for(int row = 0; row < int.length; row++)
for(int col = 0; col < int[].length; col++)
if(data[row][col] == element) return new Pair(row, col);
return new Pair(-1, -1);
}https://stackoverflow.com/questions/36138721
复制相似问题