C# solution: shrink 4 edges


  • 0
    B
    public class Solution 
    {
        public IList<int> SpiralOrder(int[,] matrix) 
        {
            var row = matrix.GetLength(0);
            var col = matrix.GetLength(1);
    
            var result = new List<int>();
            
            if (row == 0) return result;
    
            var top = 0;
            var right = col - 1;
            var bottom = row - 1;
            var left = 0;
    
            while(true)
            {
                for (int j = left; j <= right; j++)
                {
                    result.Add(matrix[top, j]);
                }
    
                top++;
    
                if (top > bottom) return result;
    
                for (int i = top; i <= bottom; i++)
                {
                    result.Add(matrix[i, right]);
                }
    
                right--;
    
                if (left > right) return result;
    
                for (int j = right; j >= left; j--)
                {
                    result.Add(matrix[bottom, j]);
                }
    
                bottom--;
    
                if (top > bottom) return result;
    
                for (int i = bottom; i >= top; i--)
                {
                    result.Add(matrix[i, left]);
                }
    
                left++;
    
                if (left > right) return result;
            }
        }
    }
    

Log in to reply
 

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