Leetcode Spiral Matrix problem solution

In the Leetcode Spiral Matrix problem solution Given an m x n matrix, return all elements of the matrix in spiral order.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

Solution in C Programming

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize){

    int* result;
    int result_index;
    int row_total;
    int col_total;
    int step_count;
    int finished;
    int curr_row;
    int curr_col;
    int row_move;
    int col_move;
    
    row_move = 0;
    col_move = 0;
    result_index = 0;
    curr_row = 0;
    curr_col = 0;
    finished = 0;
    step_count = 0;
    row_total = matrixColSize[0] - 1;
    col_total = matrixSize - 1;
    result = calloc(matrixSize * matrixColSize[0], sizeof(int));

    for (int i = 0; i < matrixColSize[0]; i++) {
        result[result_index] = matrix[curr_col][curr_row];
        curr_row++;
        result_index++;
    }
    curr_row--;
    step_count++;
    
    while (result_index < matrixSize * matrixColSize[0]) {

        if (step_count % 2 == 0) {
            row_move++;
            if (step_count % 4 == 0) {
                curr_row++;
                if (row_move >= row_total) {
                    step_count++;
                    row_total--;
                    row_move = 0;
                }
            } else {
                curr_row--;
                if (row_move >= row_total) {
                    step_count++;
                    row_total--;
                    row_move = 0;
                } 
            }

        } else {
            col_move++;
            if (step_count % 4 == 1) {
                curr_col++;
                if (col_move >= col_total) {
                    step_count++;
                    col_total--;
                    col_move = 0;
                }
            } else {
                curr_col--;
                if (col_move >= col_total) {
                    step_count++;
                    col_total--;
                    col_move = 0;
                }
            }
            
        }
        printf("%d %d\n", curr_col, curr_row);
        result[result_index] = matrix[curr_col][curr_row];
        
        result_index++;
        
    }
    *returnSize = result_index;
    
    return result;
}

Solution in C++ Programming

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
       int row = matrix.size();

       if (row == 0) 
           return vector<int>();

       int column = matrix[0].size();
    
       vector<int> result;
       int r0=0, c0=0; 
       int r,c;
       bool hmove=false, vmove=false;

       while(r0 < row && c0 < column) {
           r = r0; c = c0;
           result.push_back(matrix[r][c]);

           // travel from left to right
           while(c+1 < column) {
               c++;
               result.push_back(matrix[r][c]);
               hmove=true;
           }

           
           // travel from top to bottom
           while(r+1 < row) {
               r++;
               result.push_back(matrix[r][c]);
               vmove=true;
           }

           if (hmove && vmove) {
               // travel from right to left
               while(c-1 >= c0 ) {
                   c--;
                   result.push_back(matrix[r][c]);
               }

               // travel from bottom to top
               while(r-1 > r0 ) {
                   r--;
                   result.push_back(matrix[r][c]);
               }
           }

           r0=r;
           c0=c+1;
           row = row - 1;
           column = column - 1;
           hmove=vmove=false;
       }
        
       return  result;
    }
};

Solution in Java Programming

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new LinkedList<>(); 
        if (matrix == null || matrix.length == 0) return res;
        int n = matrix.length, m = matrix[0].length;
        int up = 0,  down = n - 1;
        int left = 0, right = m - 1;
        while (res.size() < n * m) {
            for (int j = left; j <= right && res.size() < n * m; j++)
                res.add(matrix[up][j]);
            
            for (int i = up + 1; i <= down - 1 && res.size() < n * m; i++)
                res.add(matrix[i][right]);
                     
            for (int j = right; j >= left && res.size() < n * m; j--)
                res.add(matrix[down][j]);
                        
            for (int i = down - 1; i >= up + 1 && res.size() < n * m; i--) 
                res.add(matrix[i][left]);
                
            left++; right--; up++; down--; 
        }
        return res;
    }
}

Solution in Python Programming

class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        l = []
        while matrix and len(matrix) > 0:
            l.append(matrix.pop(0)[:])
            self.reverse(matrix)
            matrix = self.transpose(matrix)
        flat_list = []
        for sublist in l:
            for item in sublist:
                flat_list.append(item)

        return flat_list
        
        
    def reverse(self, matrix):
        if len(matrix) > 0:
            for i in range(len(matrix)):
                matrix[i].reverse()

    def transpose(self, matrix):
        if len(matrix) > 0:
            return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]

Solution in C# Programming

public class Solution {
    public IList<int> SpiralOrder(int[][] matrix) {
        var m = matrix.Length;
        var n = matrix[0].Length;
        return Walk(matrix, m, n, 0)
            .Take(m * n)
            .ToList();
    }
    
    private IEnumerable<int> Walk(int[][] matrix, int m, int n, int iteration)
    {        
        var workDone = false;
        
        int[] topRow = null;
        if (iteration < m)
        {
            topRow = matrix[iteration];
            for (var i = iteration; i < n - iteration; i++)
            {
                workDone = true;
                var number = topRow[i];
                yield return number;
            }
        }
        
        for (var rowNum = iteration + 1; rowNum < m - iteration; rowNum++)
        {
            workDone = true;
            var row = matrix[rowNum];
            if (n - iteration - 1 >= 0)
            {
                var number = row[n - iteration - 1];
                yield return number;
            }
        }        
        
        if (m - iteration - 1 > 0)
        {
            var bottomRow = matrix[m - iteration - 1];
            if (topRow != bottomRow)
            {
                for (var i = n - iteration - 2; i >= iteration; i--)
                {
                    workDone = true;
                    var number = bottomRow[i];
                    yield return number;
                }
            }
        }
        
        if (iteration != n - iteration - 1)
        {
            for (var rowNum = m - iteration - 2; rowNum >= iteration + 1; rowNum--)
            {
                workDone = true;
                var row = matrix[rowNum];
                
                if (iteration < n)
                {
                    var number = row[iteration];
                    yield return number;
                }
            }
        }
        
        
        if (workDone)
        {
            var subsequentWalk = Walk(matrix, m, n, iteration + 1);
            foreach (var result in subsequentWalk)
            {
                yield return result;
            }
        }
    }
}

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *