// C# program to count number // of ways to arrange three // types of balls such that no // two balls of same color // are adjacent to each other using System; class GfG { // Returns count of arrangements where last placed ball // is 'last'. 'last' is 0 for 'p', 1 for 'q', and 2 for // 'r' static int countUtil(int p, int q, int r, int last, int[, , , ] memo) { // If number of balls of any color becomes less than // 0, the number of ways to arrange them is 0. if (p < 0 || q < 0 || r < 0) return 0; // Base cases: when only one ball of each type is // left if (p == 1 && q == 0 && r == 0 && last == 0) return 1; if (p == 0 && q == 1 && r == 0 && last == 1) return 1; if (p == 0 && q == 0 && r == 1 && last == 2) return 1; // If this subproblem is already evaluated // (memoized), return the stored result if (memo[p, q, r, last] != -1) return memo[p, q, r, last]; // Recursive calls to calculate number of // arrangements based on the last ball if (last == 0) { // If the last ball is P, the next ball can be Q // or R memo[p, q, r, last] = countUtil(p - 1, q, r, 1, memo) + countUtil(p - 1, q, r, 2, memo); } else if (last == 1) { // If the last ball is Q, the next ball can be P // or R memo[p, q, r, last] = countUtil(p, q - 1, r, 0, memo) + countUtil(p, q - 1, r, 2, memo); } else { // If the last ball is R, the next ball can be P // or Q memo[p, q, r, last] = countUtil(p, q, r - 1, 0, memo) + countUtil(p, q, r - 1, 1, memo); } // Return the computed result and store it in the // memoization table return memo[p, q, r, last]; } // Wrapper function to initialize memoization table and // call countUtil static int countWays(int p, int q, int r) { // Create a 4D array for memoization with size (p+1) // x (q+1) x (r+1) x 3 int[, , , ] memo = new int[p + 1, q + 1, r + 1, 3]; // Initialize all elements of the memo array to -1 for (int i = 0; i <= p; i++) { for (int j = 0; j <= q; j++) { for (int k = 0; k <= r; k++) { for (int l = 0; l < 3; l++) { memo[i, j, k, l] = -1; } } } } // Call countUtil for all possible last ball types // (0, 1, 2) int ans = countUtil(p, q, r, 0, memo) + countUtil(p, q, r, 1, memo) + countUtil(p, q, r, 2, memo); return ans; } static void Main() { int p = 1, q = 1, r = 1; int res = countWays(p, q, r); Console.WriteLine(res); } }