二维数组的递归方法(java) [英] recursion method with 2d array (java)

查看:88
本文介绍了二维数组的递归方法(java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须写一个方法,该方法接收一个二维整数数组的参数.该方法返回整数总和最大的行数.我只允许使用递归!不允许循环!-当然,我需要创建一个私有方法,将一行作为单个数组求和,然后我必须执行另一个比较行的私有方法,但它并没有真正起作用,因为我写的方法仅适用于一维数组,我需要比较二维数组中的一行..

i have to write a method, The method receives a parameter of two-dimensional array of integers. The method returns the number of the row which has the highest sum of the integers.I'm allowed to use only recursion! no loops allowed!-of course i need to make a private method that will sum a row as a single array and then i have to do another private method that compares the rows, but it doesn't really work since the method i wrote is only for a 1d array, and i need to compare a row from a 2d array..

感谢所有的帮助..

我的一些代码:

private  int rowSum(int[] array, int index) {//the sum of an array(1d array)
        if (index == array.length)
            return 0;
        else
            return array[index] + rowSum(array, index + 1);
    }

**public int maxRow(int[][] a){------!!!---the problem...

    }**

推荐答案

代码:

public class MainClass {
    static  int contents[][] = { {1, 2 , 3, 4} , { 4, 5, 8, 7}, { 4, 2, 8, 7}, { 4, 5, 0, 7} };
    public static void main(String[] args) 
    {
        System.out.println(getIndexOfRowWithHighestSum(contents, 0, 0));
    }
    public static int getIndexOfRowWithHighestSum(int[][] twoDAray, int currentIndex,int indexWithHighestSum){
        if(currentIndex>=twoDAray.length){
            return indexWithHighestSum;
        }
        int sum1 = getSumOfArray(twoDAray[currentIndex], 0) ;
        int sum2 = getSumOfArray(twoDAray[indexWithHighestSum], 0);

        indexWithHighestSum = (sum1 > sum2)?currentIndex:indexWithHighestSum;

        return getIndexOfRowWithHighestSum(twoDAray, currentIndex+1,indexWithHighestSum);
    }
    public static int getSumOfArray(int[] array, int currentIndex){
        if(currentIndex>=array.length){
            return 0;
        }
        return array[currentIndex]+getSumOfArray(array,currentIndex+1);
    }
}

这篇关于二维数组的递归方法(java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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