private static long findCycleSum(int prevVal, int firstVal, int numChecked, boolean checked[], boolean polyagonals[][][]) {

        if (numChecked ==polyagonals.length && prevVal%100 == firstVal/100)
            return 0;

        int baseIdx = prevVal % 100;

        for (int p = 0;p<polyagonals.length;p++)
            if (!checked[p]) {
                checked[p] = true;

                for (int i = 10;i<polyagonals[p][baseIdx].length;i++)
                    if (polyagonals[p][baseIdx][i]) {
                        int currNum = baseIdx * 100 + i;
                        long retVal = findCycleSum(
                                currNum,
                                (firstVal==0?currNum:firstVal),
                                numChecked+1,
                                checked,
                                polyagonals);
                        if (retVal>=0)
                            return currNum + retVal;

                    }

                checked[p] = false;
            }

         return -1;
    }