C# O(N) Simple Spiral traversal logic (Works for other languages as well)


  • 0
    S
    public IList<int> SpiralOrder(int[,] matrix)
    {
        IList<int> spiralList = new List<int>();
    
        int lpCnt;
        int topRowIndx = 0;
        int bottomRowIndx = matrix.GetLength(0) - 1;
    
        int leftColIndx = 0;
        int rightColIndx = matrix.GetLength(1) -1;
    
        while (leftColIndx <= rightColIndx && topRowIndx <= bottomRowIndx)
        {
            //Top Row Move Left to Right---->
            for (lpCnt = leftColIndx; lpCnt <= rightColIndx; lpCnt++)
            {
                spiralList.Add(matrix[topRowIndx, lpCnt]);
            }
    
            topRowIndx++; // Move Down to Next Row. (step down for next iteration)
    
            //Right Column Move Down ↓ 
            for (lpCnt = topRowIndx; lpCnt <= bottomRowIndx; lpCnt++)
            {
                spiralList.Add(matrix[lpCnt, rightColIndx]);
            }
    
            rightColIndx--; // Move Left to Inside Column.
    
            // If boundaries are crossed, it means we are done with traversal.
            if (leftColIndx > rightColIndx || topRowIndx > bottomRowIndx)  
                break;
    
            //Bottom Row Move Right to Left <------
            for (lpCnt = rightColIndx; lpCnt >= leftColIndx; lpCnt--)
            {
                spiralList.Add(matrix[bottomRowIndx, lpCnt]);
            }
    
            bottomRowIndx--; //Move Up to Inside Row. 
    
            //Left Column Move Up ↑
            for (lpCnt = bottomRowIndx; lpCnt >= topRowIndx; lpCnt--)
            {
                spiralList.Add(matrix[lpCnt, leftColIndx]);
            }
    
            leftColIndx++; // Move Right to Next
        }
    
        return spiralList;
    }

Log in to reply
 

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