Open In App

Create Spiral Matrix from Array using Direction Arrays

Last Updated : 12 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] and two values n and m, the task is to fill a matrix of size n*m in a spiral (or circular) fashion (clockwise) with given array elements.

Examples:  

Input: n = 4, m = 4, arr []= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
Output : [[1, 2, 3, 4],
[12, 13, 14, 5],
[11, 16, 15, 6],
[10, 9, 8, 7]]

Input: n = 3, m = 4, arr =[1, 8, 6, 3, 8, 6, 1, 6, 3, 2, 5, 3]
Output : [[1, 8, 6, 3],
[2, 5, 3, 8],
[3, 6, 1, 6]]

We have already discussed an alternate approach in Create Spiral Matrix from Array. In this post, we will discuss an approach using direction arrays.

Approach:

The idea is to simulate the spiral traversal using direction arrays to keep track of the movement (right, down, left, up) and change direction when we hit the boundary or an already filled cell.

  1. Initialize a 2D matrix with -1 to store the result matrix.
  2. Use direction arrays dr and dc to represent right, down, left, and up movements.
  3. Start from the top-left cell and follow the direction arrays to visit each cell.
  4. Change direction when encountering a boundary or a filled cell.
  5. Continue until all cells are filled.
C++
// C++ program to create a spiral matrix from given array

#include <iostream>
#include <vector>
using namespace std;

vector<vector<int>> spiralFill(int n, int m, vector<int> &arr) {
    vector<vector<int>> res(n, vector<int>(m, -1));

    // Change in row index for each direction
    vector<int> dr = { 0, 1, 0, -1 };

    // Change in column index for each direction
    vector<int> dc = { 1, 0, -1, 0 };

    // Initial direction index (0 corresponds to 'right')
    int dirIdx = 0;

    int index = 0;
    int r = 0, c = 0;

    while (index < arr.size()) {
        res[r][c] = arr[index];
        index++;

        // The next cell indices
        int newR = r + dr[dirIdx];
        int newC = c + dc[dirIdx];

        // Check if the next cell is out of bounds or
        // it is already filled, then update the direction
        if (newR < 0 || newR == n || newC < 0 || newC == m
            					|| res[newR][newC] != -1) {
            dirIdx = (dirIdx + 1) % 4;

            newR = r + dr[dirIdx];
            newC = c + dc[dirIdx];
        }

        // Update the cells
        r = newR;
        c = newC;
    }

    return res;
}

int main() {
    int m = 4, n = 4;
    vector<int> arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                       11, 12, 13, 14, 15, 16};
    vector<vector<int>> res = spiralFill(n, m, arr);

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cout << res[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}
Java
// Java program to create a spiral matrix from given array

import java.util.*;

class GfG {

    static int[][] spiralFill(int n, int m, int[] arr) {
        int[][] res = new int[n][m];

        // Initialize result array with -1
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                res[i][j] = -1;
            }
        }

        // Change in row index for each direction
        int[] dr = {0, 1, 0, -1};

        // Change in column index for each direction
        int[] dc = {1, 0, -1, 0};

        // Initial direction index (0 corresponds to 'right')
        int dirIdx = 0;

        int index = 0;
        int r = 0, c = 0;

        while (index < arr.length) {
            res[r][c] = arr[index];
            index++;

            // The next cell indices
            int newR = r + dr[dirIdx];
            int newC = c + dc[dirIdx];

            // Check if the next cell is out of bounds or
            // it is already filled, then update the direction
            if (newR < 0 || newR == n || newC < 0 || newC == m
                    || res[newR][newC] != -1) {
                dirIdx = (dirIdx + 1) % 4;

                newR = r + dr[dirIdx];
                newC = c + dc[dirIdx];
            }

            // Update the cells
            r = newR;
            c = newC;
        }

        return res;
    }

    public static void main(String[] args) {
        int m = 4, n = 4;
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                     11, 12, 13, 14, 15, 16};
        int[][] res = spiralFill(n, m, arr);

        // Printing the result 2D array
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                System.out.print(res[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Python
# Python program to create a spiral matrix from given array

def spiralFill(n, m, arr):
    res = [[-1] * m for _ in range(n)]

    # Change in row index for each direction
    dr = [0, 1, 0, -1]

    # Change in column index for each direction
    dc = [1, 0, -1, 0]

    # Initial direction index (0 corresponds to 'right')
    dirIdx = 0

    index = 0
    r, c = 0, 0

    while index < len(arr):
        res[r][c] = arr[index]
        index += 1

        # The next cell indices
        newR = r + dr[dirIdx]
        newC = c + dc[dirIdx]

        # Check if the next cell is out of bounds or
        # it is already filled, then update the direction
        if newR < 0 or newR == n or newC < 0 or newC == m \
        						 or res[newR][newC] != -1:
            dirIdx = (dirIdx + 1) % 4

            newR = r + dr[dirIdx]
            newC = c + dc[dirIdx]

        # Update the cells
        r = newR
        c = newC

    return res


if __name__ == "__main__":
    m, n = 4, 4
    arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
           11, 12, 13, 14, 15, 16]
    res = spiralFill(n, m, arr)

    for i in range(n):
        for j in range(m):
            print(res[i][j], end=" ")
        print()
C#
// C# program to create a spiral matrix from given array

using System;

class GfG {
    static int[,] SpiralFill(int n, int m, int[] arr) {
        int[,] res = new int[n, m];

        // Change in row index for each direction
        int[] dr = { 0, 1, 0, -1 };

        // Change in column index for each direction
        int[] dc = { 1, 0, -1, 0 };

        // Initial direction index (0 corresponds to 'right')
        int dirIdx = 0;

        int index = 0;
        int r = 0, c = 0;

        while (index < arr.Length) {
            res[r, c] = arr[index];
            index++;

            // The next cell indices
            int newR = r + dr[dirIdx];
            int newC = c + dc[dirIdx];

            // Check if the next cell is out of bounds or
            // it is already filled, then update the direction
            if (newR < 0 || newR == n || newC < 0 || newC == m || 
                							res[newR, newC] != 0) {
                dirIdx = (dirIdx + 1) % 4;

                newR = r + dr[dirIdx];
                newC = c + dc[dirIdx];
            }

            // Update the cells
            r = newR;
            c = newC;
        }

        return res;
    }

    static void Main() {
        int m = 4, n = 4;
        int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
        int[,] res = SpiralFill(n, m, arr);

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                Console.Write(res[i, j] + " ");
            }
            Console.WriteLine();
        }
    }
}
JavaScript
// Javascript program to create a spiral
// matrix from given array

function spiralFill(n, m, arr) {
    let res = new Array(n).fill().map(() => new Array(m).fill(-1));

    // Change in row index for each direction
    let dr = [0, 1, 0, -1];

    // Change in column index for each direction
    let dc = [1, 0, -1, 0];

    // Initial direction index (0 corresponds to 'right')
    let dirIdx = 0;

    let index = 0;
    let r = 0, c = 0;

    while (index < arr.length) {
        res[r][c] = arr[index];
        index++;

        // The next cell indices
        let newR = r + dr[dirIdx];
        let newC = c + dc[dirIdx];

        // Check if the next cell is out of bounds or
        // it is already filled, then update the direction
        if (newR < 0 || newR === n || newC < 0 || newC === m
        						|| res[newR][newC] !== -1) {
            dirIdx = (dirIdx + 1) % 4;

            newR = r + dr[dirIdx];
            newC = c + dc[dirIdx];
        }

        // Update the cells
        r = newR;
        c = newC;
    }

    return res;
}

// Driver Code
let m = 4, n = 4;
let arr = [
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
];
let res = spiralFill(n, m, arr);
res.forEach(row => console.log(row.join(" ")));

Output
1 2 3 4 
12 13 14 5 
11 16 15 6 
10 9 8 7 

Time complexity: O(n*m) where n is number of rows and m is number of columns of a given matrix
Auxiliary Space: O(1)


Article Tags :
Practice Tags :

Similar Reads