ivandrofly

Matchsticks to Square - Leetcode 473 -CSharp

Aug 26th, 2025 (edited)
394
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.30 KB | None | 0 0
  1. // Sample input arrays
  2.  
  3. int[] invalidInput = [0, 1, 2, 2, 2];
  4. int[] input = [1, 1, 2, 2, 2];
  5.  
  6. // Test the MakeSquare function with both inputs
  7. Console.WriteLine(MakeSquare(invalidInput) ? "Has solution" : "No solution");
  8. Console.WriteLine(MakeSquare(input) ? "Has solution" : "No solution");
  9. return;
  10.  
  11. static bool MakeSquare(int[] matchSticks) // root function that checks if matchsticks can form a square
  12. {
  13.     const int sideCount = 4;
  14.     // Calculate target length that each side should have (total length / 4 sides)
  15.     int targetLength = matchSticks.Sum() / 4;
  16.     // Array to track length of each side as we build the square
  17.     int[] sides = new int[4];
  18.  
  19.     // Check if total length can be evenly divided into 4 equal sides
  20.     if (Math.Abs(matchSticks.Sum() / sideCount - targetLength) > 0)
  21.     {
  22.         return false;
  23.     }
  24.  
  25.     // Sort matchsticks in descending order to optimize backtracking
  26.     // Larger matchsticks are harder to place, so try them first
  27.     Array.Sort(matchSticks, (a, b) => b.CompareTo(a));
  28.  
  29.     return Backtrack(0);
  30.  
  31.     // Recursive backtracking function to try different matchstick placements
  32.     bool Backtrack(int matchStickIndex)
  33.     {
  34.         // Base case: if all matchsticks have been placed successfully
  35.         if (matchStickIndex == matchSticks.Length)
  36.         {
  37.             return true;
  38.         }
  39.  
  40.         // Try placing current matchstick on each side
  41.         for (int sideIdx = 0; sideIdx < 4; sideIdx++)
  42.         {
  43.             // Check if adding current matchstick would not exceed target length
  44.             if (sides[sideIdx] + matchSticks[matchStickIndex] <= targetLength)
  45.             {
  46.                 // Place matchstick on current side
  47.                 sides[sideIdx] += matchSticks[matchStickIndex];
  48.                 // Recursively try to place remaining matchsticks
  49.                 if (Backtrack(matchStickIndex + 1))
  50.                 {
  51.                     return true;
  52.                 }
  53.  
  54.                 // Backtrack by removing matchstick if solution not found
  55.                 sides[sideIdx] -= matchSticks[matchStickIndex];
  56.             }
  57.         }
  58.  
  59.         // No valid solution found for current matchstick
  60.         return false;
  61.     }
  62. }
  63.  
  64. // Matchsticks to Square - Leetcode 473 - Python
  65. // https://www.youtube.com/watch?v=hUe0cUKV-YY&t=354s
Advertisement
Add Comment
Please, Sign In to add comment