#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    1
    Rep Power
    0

    Recursion problem


    Hi! I need help with my homework.
    We are learning 2d arrays and the program is supposed to check whether there is a connection of trues from the bottom of the board to the top. And I keep getting java.lang.StackOverflow. I think it's because there is an infinite loop when there is two trues side by side. Can anybody suggest me a solution? Thanks in advance.

    My code:
    public static boolean recurse(boolean[][] board,int row, int col)
    {
    if (col < 0 || col > board[0].length-1)
    return false;
    else
    {
    if (row == 0 && board[row][col] == true)
    return true;
    else if (board[row][col] == false)
    return false;
    else
    {
    if (recurse(board,row-1,col) == true || recurse(board,row,col+1) == true || recurse(board,row,col-1) == true)
    return true;
    else
    return false;
    }
    }
    }

    public static boolean isConnected(boolean[][] board)
    {
    for (int i = 0 ; i < board[0].length; i++)
    {
    if (board[board.length-1][i] == true)
    {
    if (recurse(board ,board.length - 2, i) == true || recurse(board , board.length-1 , i+1) == true || recurse(board , board.length-1 , i-1) == true)
    return true;
    }
    }
    return false;
    }
  2. #2
  3. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,714
    Rep Power
    348
    What is in some of the stack trace that shows where the execution was?

    Can you edit your post and wrap the code with code tags to make it easier to read and understand?

    Can you post a version of the code that can be compiled, executed and show the problem?

IMN logo majestic logo threadwatch logo seochat tools logo