private static bool SearchBag(string color, IBag bag) { AllUniqueBags.ClearUsed(); Queue <IBag> queue = new Queue <IBag>(); bag.Used = true; foreach (var itemBag in bag.InsideBags) { if (!itemBag.Used) { queue.Enqueue(itemBag); } } while (queue.Count > 0) { var qB = queue.Dequeue(); if (qB.Header.Color == color) { return(true); } qB.Used = true; foreach (var itemBag in qB.InsideBags) { if (!itemBag.Used) { itemBag.Used = true; queue.Enqueue(itemBag); } } } return(false); }
private static int CountBag(IBag bag) { int countBags = 0; AllUniqueBags.ClearUsed(); var queue = new Queue <Tuple <int, IBag> >(); foreach (var itemBag in bag.InsideBags) { if (!itemBag.Used) { countBags += itemBag.Count; queue.Enqueue(new Tuple <int, IBag>(itemBag.Count, itemBag)); } } while (queue.Count > 0) { var qB = queue.Dequeue(); foreach (var itemBag in qB.Item2.InsideBags) { if (!itemBag.Used) { countBags += qB.Item1 * itemBag.Count; queue.Enqueue(new Tuple <int, IBag>(qB.Item1 * itemBag.Count, itemBag)); } } } return(countBags); }
static void Main(string[] args) { string[] input = ReadInput("../../input.txt"); var regexBaseBag = new Regex(@"^\w+ \w+ bags contain"); var regexBaseBagReplace = new Regex(@" bags contain"); var regexInsideBag = new Regex(@"\d+ \w+ \w+ bag[s,|s.|.]"); var regexCountBag = new Regex(@"^\d+"); var regexBagName = new Regex(@"^\w+ \w+"); AllBags = new List <IBag>(); foreach (var item in input) { var BagName = regexBaseBagReplace.Replace(regexBaseBag.Match(item).Value, ""); var bag = AllUniqueBags.GetBag(BagName); var right = regexBaseBag.Replace(item, "").Trim(); if (!right.Equals("no other bags.")) { var matchs = regexInsideBag.Matches(right); foreach (object match in matchs) { var s = match.ToString(); if (int.TryParse(regexCountBag.Match(s).Value, out int k)) { s = regexCountBag.Replace(s, "").Trim(); string name = regexBagName.Match(s).Value; bag.InsideBags.Add(new BagHeaderWithCount(AllUniqueBags.GetBag(name), k)); } else { throw new Exception($"Строка {s} имеет не верный формат"); } } } AllBags.Add(bag); } Console.WriteLine(CountBag(AllUniqueBags.GetBag("shiny gold"))); }