Java 1D Array (Part 2)

  • + 0 comments

    public static boolean canWin(int leap, int[] game) { return canWinHelper(leap, game, 0); }

    // Helper method to recursively check if the game can be won private static boolean canWinHelper(int leap, int[] game, int pos) { // Base cases if (pos < 0 || game[pos] == 1) return false; // Out of bounds or already visited if (pos >= game.length - 1 || pos + leap >= game.length) return true; // Win condition

    // Mark the current position as visited
    game[pos] = 1;
    
    // Recursive checks for possible moves
    return canWinHelper(leap, game, pos + leap) || // Jump forward
           canWinHelper(leap, game, pos + 1) ||   // Walk forward
           canWinHelper(leap, game, pos - 1);     // Walk backward
    

    }