public boolean isConnected(int row, int col) { //helper Method
int i;
int j;
if (BOARD[row][col].isEmpty())
return false;
for (i = row; i > 0; i--)
if (hasRed(i, col))
return true;
else if (isEmpty(i, col))
break;
for (i = row; i < ROWS; i++)
if (hasRed(i, col))
return true;
else if (isEmpty(i, col))
break;
for (i = col; i < COLS; i++)
if (hasRed(row, i))
return true;
else if (isEmpty(row, i))
break;
for (i = col; i > 0; i--)
if (hasRed(row, i))
return true;
else if (isEmpty(row, i))
break;
for (i = row, j = col; i > 0 && j < COLS; i--, j++)
if (hasRed(i, j))
return true;
else if (isEmpty(i, j))
break;
for (i = row, j = col; i < ROWS && j > 0; i++, j--)
if (hasRed(i, j))
return true;
else if (isEmpty(i, j))
break;
for (i = row, j = col; i > 0 && j > 0; i--, j--)
if (hasRed(i, j))
return true;
else if (isEmpty(i, j))
break;
for (i = row, j = col; i < ROWS && j < COLS; i++, j++)
if (hasRed(i, j))
return true;
else if (isEmpty(i, j))
break;
return false;
}
//The main Method which may cause an exception the algorithm after many test cases tried always terminates if there is a true solution but may or may not terminate for a false one the reason I guess is that the recursion step does not simplify the original problem but actually expands it ! in order to have a chance to get the correct solution, the problem is that in certain conditions which certainly should return false the algorithm cannot terminate as it keep checking previously solved subproblems and so on.
public boolean isConnected2(int rowCurr, int colCurr) {
if (rowCurr >= ROWS || rowCurr < 0 || colCurr < 0 || colCurr >= COLS)
return false; //Base case 1 reached bounds of the 2d array
if (isEmpty(rowCurr, colCurr))
return false;
if (isConnected(rowCurr, colCurr)) // base case 2 current piece is connected according to the method above
return true;
else {
return isConnected2(rowCurr + 1, colCurr + 1)
|| isConnected2(rowCurr - 1, colCurr - 1)
|| isConnected2(rowCurr + 1, colCurr - 1)
|| isConnected2(rowCurr - 1, colCurr + 1)
|| isConnected2(rowCurr - 1, colCurr - 1)
|| isConnected2(rowCurr + 1, colCurr)
|| isConnected2(rowCurr - 1, colCurr)
|| isConnected2(rowCurr, colCurr + 1)
|| isConnected2(rowCurr, colCurr - 1);
// if any of the above calls returns true we are done
}
}
The thing is I am not sure how to handle the special cases that cause the algorithm to recurse to infinitely, And I am sure due to the nature of(||) operator that if there is a true solution IT WILL TERMINATE. So is it not better in this case to just handle the StackOverFlow error and treat it as a false return for the method ??
Don’t EVER leave a stack overflow in your program. Letting it happen and catching it is a huge burden on the JVM. Fix your recursion so that it can’t happen.