Java - 如何使用递归在2D数组中查找元素

时间:2014-03-04 18:05:07

标签: java arrays recursion

问题是:给定一个名为int的2D data数组,如果数组中的任何值等于给定元素,则返回true。否则返回false。您的程序应该在任一维度上使用任意大小的数组,包括不规则(或不规则)数组。例如:

int[][] table = new int[][] { {5, 2, 8, 5, 61}, {3, 9, 6}, {10, 42, 53, 45}};

searchTable(table, 45) returns true

searchTable(table, 100) returns false

警告:

  

不能使用任何一种循环,方法不能是静态的,不能使用类实例变量。

到目前为止,这是我的代码:

public boolean searchTable(int[][] data, int element){
    boolean result = false;
    int a = searchRow(data[data.length-1], data.length -1);
    int b = searchCol(data[a], data.length -1);
    if (data[a][b] == element)
        result = true;
    else
        result = false;
    return result;
}

public int searchRow(int [] row, int index)
{ 
    if (row.length != 0)
        return index;
    else
    {
        return searchRow(row, index + 1);
    }
}

public int searchCol(int [] col, int index) 
{
    if (col.length != 0 )
        return index;
    else
    {
        return searchCol(col, index + 1);
    }
 }

我的输出为false

2 个答案:

答案 0 :(得分:2)

这是一种以递归方式解决问题的方法,

public boolean searchTable(int[][] data, int element) {
    return searchTable(data, element, 0);
}

private boolean searchTable(int[][] data, int element, int p) {
    if (p < 0 || p > data.length) {
        return false;
    }
    int[] row = getRow(data, p);
    if (searchRow(row, element, 0)) {
        return true;
    }
    return searchTable(data, element, 1 + p);
}

private boolean searchRow(int[] data, int element, int p) {
    if (data == null || p >= data.length) {
        return false;
    }
    if (data[p] == element) {
        return true;
    }
    return searchRow(data, element, 1 + p);
}

public int[] getRow(int[][] in, int x) {
    if (in == null || x >= in.length) {
        return null;
    }
    return in[x];
}

public static void main(String[] args) {
    // I named the class Question.
    Question question = new Question();
    int[][] table = new int[][] { { 5, 2, 8, 5, 61 }, { 3, 9, 6 },
            { 10, 42, 53, 45 } };
    System.out.println(question.searchTable(table, 45));
    System.out.println(question.searchTable(table, 100));
}

输出

true
false

答案 1 :(得分:1)

将返回结果的一种方法:

public class RecursiveSearch{

    int rowCount = 0;
    int columnCount = 0;
    boolean result = false;

    public boolean searchTable(int[][] data, int element){

        if(data[rowCount].length==columnCount)
        {
            rowCount++;
            columnCount=0;
        }

        if(data.length > rowCount)
        {
            if(data[rowCount][columnCount] == element)
            {
                result = true;
            }
            else
            {
                columnCount++;
                searchTable(data, element);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[][] table = new int[][] { {5, 2, 8, 5, 61}, {3, 9, 6}, {10, 42, 53, 45}};
        System.out.println(new RecursiveSearch().searchTable(table, 45));
    }
}