Java 1D Array (Part 2)

  • + 0 comments
    public static boolean canWin(int leap, int[] game) {
        // Return true if you can win the game; otherwise, return false.
        return canWinHelper(0, leap, game);
    }
    
    static boolean canWinHelper(int currentIndex, int leap, int[] game) {
        if( currentIndex >= game.length || game[currentIndex]==1 ){
            return false;
        }
        if (currentIndex == game.length - 1 || currentIndex + leap >= game.length) {
            return true;
        }
        game[currentIndex] = 1; 
        boolean canWinFromNext = canWinHelper(currentIndex + 1, leap, game);
        boolean canWinFromBack = (currentIndex - 1 >= 0) && canWinHelper(currentIndex - 1, leap, game);
        boolean canWinFromLeap = canWinHelper(currentIndex + leap, leap, game);
        game[currentIndex] = 0; 
        return canWinFromNext || canWinFromBack || canWinFromLeap;
    }