using System.Collections.Generic;
static Dictionary<string, string> cells = new Dictionary<string, string>();
static Dictionary<string, int> cellValues = new Dictionary<string, int>();
static HashSet<string> visitedCells = new HashSet<string>();
static void SetCell(string cellAddr, string cellValue)
if (cellValue == null || cellValue.Length == 0) cells.Remove(cellAddr);
else cells[cellAddr] = cellValue;
static int GetValue(string cellAddr)
if (cellValues.ContainsKey(cellAddr)) return cellValues[cellAddr];
if (visitedCells.Contains(cellAddr)) throw new Exception("cells form cycle");
visitedCells.Add(cellAddr);
if (!cells.TryGetValue(cellAddr, out cell)) cellValue = 0;
char firstChar = cell[0];
var sumCells = cell.Substring(1).Split('+');
foreach (var sumCell in sumCells) cellValue += GetValue(sumCell);
else if (!int.TryParse(cell, out cellValue)) throw new Exception("Invalid cell");
cellValues[cellAddr] = cellValue;
public static void Main()
SetCell("F22", "=F18+F18");
SetCell("B52", "=B2+F22+B2+F22+F35");
Console.WriteLine("Cell B52: " + GetValue("B52"));
Console.WriteLine("Cell B52: " + GetValue("B52"));