繁体   English   中英

java 中的递归 2D 5x5 计数“a”function

[英]Recursive 2D 5x5 counting 'a' function in java

我必须编写一个方法来返回矩阵中'a'字符的计数,但我必须使用递归来完成它,它必须是 O(n.log(n))。

这是我的非递归代码:

public static int acount(char[][] mat) {
    int result = 0;

    int i = 0;
    int j = 0;

    while (i <= 4) {
        if (mat[i][j] == 'a') {
            result++;
            j++;
        }
        if (mat[i][j] == 'b') {
            i++;
            j = 0;
        }
    }
    return result;
}

这是我尝试过的,但出现错误:“线程“主”java.lang.StackOverflowError 中的异常”:

public static int acount(char[][] mat) {
    int result = 0;

    int i = 0;
    int j = 0;

    while (mat[i][j] == 'a') {
        
        result++;
        j++;
        
    }

    if (i < 5) {
        
        i++;
        j = 0;

    } else {
        
        return result;
        
    }
    
    return acount(mat);
    
}

这是主要代码:

public static void main(String[] args) {
    
    int n = 5;
    Random rand = new Random();
    char[][] input = new char[n][n];
    for (int i = 0; i < n; i++) {
        int a_num = rand.nextInt(n);
        for (int j = 0; j < a_num; j++) {
            input[i][j] = 'a';
        }
        for (int j = a_num; j < n; j++) {
            input[i][j] = 'b';
        }
    }       
    System.out.println(Arrays.deepToString(input));     
    System.out.println(acount(input));

}

}

怎么解决?

好的,让我们从您的原始版本开始。

public static int acount(char[][] mat) {
    int result = 0;

    int i = 0;
    int j = 0;

    while (i <= 4) {
        if (mat[i][j] == 'a') {
            result++;
            j++;
        }
        if (mat[i][j] == 'b') {
            i++;
            j = 0;
        }
    }
    return result;
}

这段代码看起来有问题。 首先,它假设您的输入仅包含 a 或 b。 如果包含其他数据,则永远不会增加 i 或 j 并且永远循环。 看起来您还假设矩阵中的每一行都是 aab-who-cares。 也就是说,所有的 a,但你不再看第一个 b。 那是你真正想要的吗? 也许是的。

我会这样写:

for (int index1 = 0; index1 < 5; ++index1) {
     for (int index2 = 0; index2 < 5; ++index2) {
         if (mat[index1][index2] == 'a') {
             ++result;
         }
     }
}

实际上,我不会硬编码 5,而是分别使用mat.lengthmat[index1].length

至于你的堆栈溢出——这是因为你的递归永远不会结束。 你来做这件事:

    return acount(mat);

也就是说,你再次用相同的数组调用acount ,它再次调用acount ,它再次调用acount ......

唯一不会失败的方法是,如果上面的代码提前返回,它可能不会。 我认为您缺少的是每次输入acount时,都会获得新的变量,因此 i 和 j 再次从零开始。

您可以通过将i传递给acount来部分解决此问题,并且当您递归时:

return acount(mat, i+1);

这将解决一些问题,尽管我认为你的复杂性仍然是 O(n^2)。

那么我们来看看这个:

while (mat[i][j] == 'a') {
    result++;
    j++;
}

如果该行中没有任何 a 会发生什么? 它看起来超出了数组的末尾。 您正在对输入数据做出假设,这会咬到您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM