Unhelpful code, I just wanna say C# delegate is fxxkin' cool


  • 1
    O
    public class Solution
    {
        public IList<int> SpiralOrder(int[,] matrix) { return Spiral(matrix).ToList(); }
    
        IEnumerable<int> Spiral(int[,] _mtx)
        {
            if (_mtx.Length < 1) yield break;
            int i = 0, j = 0, dir = 0;
            int[] border = new int[] { _mtx.GetLength(1), _mtx.GetLength(0), -1, -1 };
            Func<int, bool>[] check_border = new Func<int, bool>[]
            {
                new Func<int, bool>(x => j < x - 1), new Func<int, bool>(x => i < x - 1),
                new Func<int, bool>(x => j > x + 1), new Func<int, bool>(x => i > x + 1),
            };
            Action[] go_next = new Action[]
            { new Action(() => j++), new Action(() => i++), new Action(() => j--), new Action(() => i--) };
            for (int k = 0; k < _mtx.Length; k++)
            {
                yield return _mtx[i, j];
                if (!check_border[dir](border[dir]))
                {
                    int narrow = (dir + 3) % 4;
                    if (narrow < 2) border[narrow]--; else border[narrow]++;
                    dir = ++dir % 4;
                }
                go_next[dir]();
            }
        }
    }

  • 0
    L

    I like these cool features in C#.


Log in to reply
 

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