Spiral Matrix I I Algorithm

The Spiral Matrix II algorithm is a unique approach to generating a matrix in a spiral pattern. It is often employed to create a square matrix, where elements are arranged in a spiral order, starting from the top left corner and moving inwards in a clockwise direction. This algorithm is useful in various applications, including image processing, data manipulation, and problem-solving tasks that require the arrangement of elements in a specific pattern. To implement the Spiral Matrix II algorithm, a two-dimensional array or matrix is initialized with the dimensions provided, typically in the form of an integer, n, where the matrix size is n x n. The algorithm then iterates through the matrix, filling each element with an incrementing value, starting from 1, while traversing the matrix in a spiral pattern. The traversal is performed using four loops, corresponding to each direction of the spiral: right, down, left, and up. These loops ensure that the matrix is filled in the correct order, with each element being assigned a unique value. The process continues until all elements in the matrix are assigned their respective values, ultimately forming the desired spiral matrix.
class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        vector<vector<int>> matrix(n, vector<int>(n, 0));
        int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};
        int x = 0;
        int y = -1;
        int k = 0;
        int count = 0;
        int horizon = true;
        int row = n;
        int col = n + 1;
        while (count < n * n) {
            int dx = dir[k%4][0];
            int dy = dir[k%4][1];
            k++;
            if (horizon) {
                horizon = false;
                col--;
                for (int i = 0; i < col; i++) {
                    x += dx;
                    y += dy;
                    count++;
                    matrix[x][y] = count;
                }
            } else {
                horizon = true;
                row--;
                for (int i = 0; i < row; i++) {
                    x += dx;
                    y += dy;
                    count++;
                    matrix[x][y] = count;
                }
            }
        }
        return matrix;
    }
};

LANGUAGE:

DARK MODE: