c# AC Solution


  • 0
    N
    public class Excel
    {
        int h;
        int w;
        int[,] excel;
        string[,][] formula;
        public Excel(int H, char W)
        {
            h = H; // 1-26
            w = W - 'A' + 1; // 1-26
            excel = new int[h, w];
            formula = new string[h, w][];
        }
    
        public void Set(int r, char c, int v)
        {
            Set(r - 1, c - 'A', v);
        }
    
        void Set(int r, int c, int v)
        {
            formula[r, c] = null;
            excel[r, c] = v;
        }
    
        public int Get(int r, char c)
        {
            return Get(r - 1, c - 'A');
        }
    
        int Get(int r, int c)
        {
            if (formula[r, c] != null)
            {
                return Calc(r, c);
            }
            else
            {
                return excel[r, c];
            }
        }
    
        int Get(string s)
        {
            var r = int.Parse(s.Substring(1)) - 1;
            var c = s[0] - 'A';
            return Get(r, c);
        }
    
        public int Sum(int r, char c, string[] strs)
        {
            return Sum(r - 1, c - 'A', strs);
        }
    
        int Sum(int r, int c, string[] strs)
        {
            formula[r, c] = strs;
            return Get(r, c);
        }
    
        int Calc(int r, int c)
        {
            var strs = formula[r, c];
            var total = 0;
            foreach (var s in strs)
            {
                total += CalcRange(s);
            }
    
            return total;
        }
        int CalcRange(string s)
        {
            var index = s.IndexOf(":");
            if (index >= 0)
            {
                var upleft = s.Substring(0, index);
                var bottomright = s.Substring(index + 1);
    
                if (upleft.Equals(bottomright))
                {
                    return Get(upleft);
                }
                else
                {
                    var ulRow = int.Parse(upleft.Substring(1)) - 1;
                    var ulCol = upleft[0] - 'A';
    
                    var brRow = int.Parse(bottomright.Substring(1)) - 1;
                    var brCol = bottomright[0] - 'A';
                    var total = 0;
                    for (var i = ulRow; i <= brRow; i++)
                    {
                        for (var j = ulCol; j <= brCol; j++)
                        {
                            if (formula[i, j] != null)
                                total += Calc(i, j);
                            else
                                total += excel[i, j];
                        }
                    }
    
                    return total;
                }
            }
            else
            {
                return Get(s);
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.