Leetcode 54 Solution

This article provides solution to leetcode question 54 (spiral-matrix)

https://leetcode.com/problems/spiral-matrix

Solution

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> res;

        int m = matrix.size();
        if (m == 0)
            return res;
        int n = matrix[0].size();

        vector<vector<int>> a;

        for (int i = 0; i < m; i++)
            a.push_back(vector<int>(n));

        int di = 0;
        int dj = 1;

        int i = 0;
        int j = 0;

        while (res.size() < m * n)
        {
            a[i][j] = 1;
            res.push_back(matrix[i][j]);

            if (di == 0 && dj == 1)
            {
                if (j + dj >= n || a[i][j + dj] == 1)
                    di = 1, dj = 0;
            }
            else if (di == 1 && dj == 0)
            {
                if (i + di >= m || a[i + di][j] == 1)
                    di = 0, dj = -1;
            }
            else if (di == 0 && dj == -1)
            {
                if (j + dj < 0 || a[i][j + dj] == 1)
                    di = -1, dj = 0;
            }
            else if (di == -1 && dj == 0)
            {
                if (i + di < 0 || a[i + di][j] == 1)
                    di = 0, dj = 1;
            }

            i += di;
            j += dj;
        }

        return res;
    }
};