Leetcode 59 Solution

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

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

Solution

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int i = 0;
        int j = 0;

        vector<vector<int>> a;

        if (n == 0)
            return a;

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

        int di = 0;
        int dj = 1;
        int k = 1;

        while (true)
        {
            a[i][j] = k;

            if (k == n * n)
                break;

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

            i += di;
            j += dj;
            k++;
        }

        return a;
    }
};