2014-01-23 80 views
0

我迷路了,请问有人能帮我吗?java递归行

我想我的函数“oddEvenRow”检查行索引0,2,4中的值是否为奇数。如果是的话返回true,如果不是返回false

这是我写的代码:

public class Matrix 
{ 
    public static int temp=0; 
    public static boolean oddEvenRow (int[][]a, int r, int c, int count) 
    { 
     if(r>4&&count==12) { 
      temp=1; 
      return false; 
     } 
     if(a[r][c]%2==0) { 
      temp=1; 
      return false; 
     } 
     else {   
      count++; 
      if(c==3)     
       oddEvenRow(a,r+2,0,count); 
      else 
       oddEvenRow(a,r,c+1,count);     
      return true; 
     }  
    } 

    public static void main(String args[]) 
    { 
     int r=0; 
     int c=0; 
     int count=0; 
     int[][]a=new int[5][4]; 
     a[0][0]=1; 
     a[0][1]=3; 
     a[0][2]=7; 
     a[0][3]=15; 
     a[1][0]=4; 
     a[1][1]=15; 
     a[1][2]=2; 
     a[1][3]=9; 
     a[2][0]=11; 
     a[2][1]=21; 
     a[2][2]=1; 
     a[2][3]=45; 
     a[3][0]=8; 
     a[3][1]=15; 
     a[3][2]=8; 
     a[3][3]=12; 
     a[4][0]=7; 
     a[4][1]=3; 
     a[4][2]=25; 
     a[4][3]=21; 
     System.out.println(oddEvenRow(a,r,c,count)); 
    } 
} 
+1

要发布的事实,而不是一个问题。 – Maroun

+1

我用'temp = 0'迷路了...又是什么问题? – radimpe

+0

为了理解递归,你必须首先理解递归。 – Fildor

回答

0

对于我count部分是多余的,因为你检查r变量的所有行 - 最后显著一行之后(4)该方法将返回。你不需要检查是否有12个号码被检查。

什么是更多temp变量作为代码中的返回值,您实际上正在使用方法本身返回 - 也是多余的。

我不明白这一点在检查使用递归值的已定义的数量,但如果你需要这样考虑以下几点:

public static boolean oddRow(int[][] a, int r, int c) { 

     //checking if we checked all rows 
     if (r > 4) { 
      return true; 
     } 
     //checking if all columns in row were checked and moving to r+2 row 
     if (c > 3) { 
      return oddRow(a, r + 2, 0); 
     } 
     //checking if current value is odd - if yes, keep checking the rest/if not, return false 
     return (a[r][c] % 2 == 0) ? oddRow(a, r, c + 1) : false; 

    } 
1

你的代码[看,我怀疑你的意思是你的问题说:“如果行0,2 ALL值,并且4是奇数...“]

无论如何,你设置短路变量'temp',但从不使用它。尝试添加一个检查你函数的顶部...

if(temp == 1) 
    return false;