Spiral Matrix 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<int> spiralOrder(vector<vector<int> > &matrix) {
        vector<int> result;
        if (matrix.empty()) {
            return result;
        }
        int row = matrix.size();
        int col = matrix[0].size() + 1;
        int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};
        int x = 0;
        int y = -1;
        int k = 0;
        int count = 0;
        bool horizon = true;
        while (count < matrix.size() * matrix[0].size()) {
            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++, count++) {
                    x += dx;
                    y += dy;
                    result.push_back(matrix[x][y]);
                }
            } else {
                horizon = true;
                row--;
                for (int i = 0; i < row; i++, count++) {
                    x += dx;
                    y += dy;
                    result.push_back(matrix[x][y]);
                }
            }
        }
        return result;
	}
};

LANGUAGE:

DARK MODE: