如何搜索元素在2D使用数组递归 [英] how to search elements in a 2d array using recursion

查看:141
本文介绍了如何搜索元素在2D使用数组递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维字符数组,我试图找到一个特定的字符使用递归。

I have a 2d char array and I'm trying to find a specific character using recursion.

public class Test {

char arry [][] = {{'1',' ','B'},
                  {'C','K','M'},
                  {'H','R','P'}
};

public Test(){
    recursion(0,0,arry[0][0]);

}
private void recursion(int row, int col, char c) {
    if(c==' '){
        System.out.print("Location: " + row + " " + col );
    }else
    {
        if(col+1<arry[0].length){
            recursion(row,col,c);
        }
                    //System.out.print(arry[0][1]);

    }

}
public static void main(String[] args) {

    new Test();
}

}

但是这是给我一个堆栈溢出。我怎么能使用递归找到一个二维数组中的元素。

but this is giving me a stack overflow. how can I find an element in a 2d array using recursion.

推荐答案

它看起来像你的,如果没有被正确执行的语句。要检查检查如果c ==,但我觉得你的意思是要检查如果数组[行] [COL] == c审核。此外,它好像你从来没有真正增加行的值山坳,因此递归本身不断发生。由于递归值永远不会改变,并且检查可以永远是真实的,这最终将导致一个计算器。

It looks like your if statement isn't being executed properly. You are checking to check if c == " ", though I think you meant it to check if array[row][col]==c. Also, it seems like you never actually increment the values of row and col, so the recursion continuously happens on itself. Since the recursion values never change, and the check can never be true, this will eventually lead to a stackoverflow.

尝试沿着这些路线的内容:

Try something along these lines:

private void recursion(int row, int col, char c) {
    if(array[row][col]==c){
        System.out.print("Location: " + row + " " + col );
    } else {
        if(col+1<array[0].length){
            recursion(row,col+1,c);
        } else if(row + 1<array[1].length){
            recursion(row+1,0,c);
        } else {
            System.out.print("Does not exist");
            //System.out.print(arry[0][1]); 
        }
    }
}

这篇关于如何搜索元素在2D使用数组递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆