Form a Spiral Matrix from the given Array

26 Nov, 2021
Given an array, the task is to form a spiral matrix 
Examples: 
Input:
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:
arr[] = { 1, 2, 3, 4, 5, 6,
          7, 8, 9, 10, 11, 12,
          13, 14, 15, 16, 17, 18 };
Output:
1   2  3  4  5 6 
14 15 16 17 18 7 
13 12 11 10  9 8
Approach: This problem is just the reverse of this problem “Print a given matrix in spiral form“. The approach to do so is: 
Traverse the given array and pick each element one by one.
Fill each of this element in the spiral matrix order.
Spiral matrix order is maintained with the help of 4 loops – left, right, top, and bottom.
Each loop prints its corresponding row/column in the spiral matrix.
Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ program to form a Spiral Matrix// from the given Array #include <bits/stdc++.h>using namespace std; #define R 3#define C 6 // Function to form the spiral matrixvoid formSpiralMatrix(int arr[], int mat[R][C]){    int top = 0,        bottom = R - 1,        left = 0,        right = C - 1;     int index = 0;     while (1) {         if (left > right)            break;         // print top row        for (int i = left; i <= right; i++)            mat[top][i] = arr[index++];        top++;         if (top > bottom)            break;         // print right column        for (int i = top; i <= bottom; i++)            mat[i][right] = arr[index++];        right--;         if (left > right)            break;         // print bottom row        for (int i = right; i >= left; i--)            mat[bottom][i] = arr[index++];        bottom--;         if (top > bottom)            break;         // print left column        for (int i = bottom; i >= top; i--)            mat[i][left] = arr[index++];        left++;    }} // Function to print the spiral matrixvoid printSpiralMatrix(int mat[R][C]){     for (int i = 0; i < R; i++) {        for (int j = 0; j < C; j++)            cout << mat[i][j] << " ";        cout << '\n';    }} // Driver codeint main(){    int arr[]        = { 1, 2, 3, 4, 5, 6,            7, 8, 9, 10, 11, 12,            13, 14, 15, 16, 17, 18 };    int mat[R][C];     formSpiralMatrix(arr, mat);    printSpiralMatrix(mat);     return 0;}
// Java program to form a Spiral Matrix// from the given Arrayclass GFG{    static final int R = 3 ;    static final int C = 6;     // Function to form the spiral matrix    static void formSpiralMatrix(int arr[], int mat[][])    {        int top = 0,            bottom = R - 1,            left = 0,            right = C - 1;             int index = 0;             while (true)        {            if (left > right)                break;                 // print top row            for (int i = left; i <= right; i++)                mat[top][i] = arr[index++];            top++;                 if (top > bottom)                break;                 // print right column            for (int i = top; i <= bottom; i++)                mat[i][right] = arr[index++];            right--;                 if (left > right)                break;                 // print bottom row            for (int i = right; i >= left; i--)                mat[bottom][i] = arr[index++];            bottom--;                 if (top > bottom)                break;                 // print left column            for (int i = bottom; i >= top; i--)                mat[i][left] = arr[index++];            left++;        }    }         // Function to print the spiral matrix    static void printSpiralMatrix(int mat[][])    {        for (int i = 0; i < R; i++)        {            for (int j = 0; j < C; j++)                System.out.print(mat[i][j] + " ");            System.out.println();        }    }         // Driver code    public static void main (String[] args)    {        int arr[] = { 1, 2, 3, 4, 5, 6,                      7, 8, 9, 10, 11, 12,                      13, 14, 15, 16, 17, 18 };                         int mat[][] = new int[R][C];             formSpiralMatrix(arr, mat);        printSpiralMatrix(mat);    }} // This code is contributed by kanugargng
# Python program to form a Spiral Matrix# from the given Array R = 3 ;C = 6; # Function to form the spiral matrixdef formSpiralMatrix(arr, mat):    top = 0;    bottom = R - 1;    left = 0;    right = C - 1;     index = 0;     while (True):                 if(left > right):            break;         # print top row        for i in range(left, right + 1):            mat[top][i] = arr[index];            index += 1;        top += 1;         if (top > bottom):            break;         # print right column        for i in range(top, bottom+1):            mat[i][right] = arr[index];            index += 1;        right -= 1;         if (left > right):            break;         # print bottom row        for i in range(right, left-1, -1):            mat[bottom][i] = arr[index];            index += 1;        bottom -= 1;         if (top > bottom):            break;         # print left column        for i in range(bottom, top-1, -1):            mat[i][left] = arr[index];            index += 1;        left += 1;# Function to print the spiral matrixdef printSpiralMatrix(mat):    for i in range(R):        for j in range(C):            print(mat[i][j],end= " ");        print(); # Driver codeif __name__ == '__main__':    arr = [ 1, 2, 3, 4, 5, 6,                7, 8, 9, 10, 11, 12,                13, 14, 15, 16, 17, 18 ];     mat= [[0 for i in range(C)] for j in range(R)];    formSpiralMatrix(arr, mat);    printSpiralMatrix(mat); # This code contributed by PrinciRaj1992
// C# program to form a Spiral Matrix// from the given Arrayusing System;     class GFG{    static readonly int R = 3;    static readonly int C = 6;     // Function to form the spiral matrix    static void formSpiralMatrix(int []arr,                                 int [,]mat)    {        int top = 0,            bottom = R - 1,            left = 0,            right = C - 1;             int index = 0;             while (true)        {            if (left > right)                break;                 // print top row            for (int i = left; i <= right; i++)                mat[top, i] = arr[index++];            top++;                 if (top > bottom)                break;                 // print right column            for (int i = top; i <= bottom; i++)                mat[i, right] = arr[index++];            right--;                 if (left > right)                break;                 // print bottom row            for (int i = right; i >= left; i--)                mat[bottom, i] = arr[index++];            bottom--;                 if (top > bottom)                break;                 // print left column            for (int i = bottom; i >= top; i--)                mat[i, left] = arr[index++];            left++;        }    }         // Function to print the spiral matrix    static void printSpiralMatrix(int [,]mat)    {        for (int i = 0; i < R; i++)        {            for (int j = 0; j < C; j++)                Console.Write(mat[i, j] + " ");            Console.WriteLine();        }    }         // Driver code    public static void Main (String[] args)    {        int []arr = { 1, 2, 3, 4, 5, 6,                      7, 8, 9, 10, 11, 12,                     13, 14, 15, 16, 17, 18 };                         int [,]mat = new int[R, C];             formSpiralMatrix(arr, mat);        printSpiralMatrix(mat);    }} // This code is contributed by 29AjayKumar
<script> // Javascript program to form a Spiral Matrix// from the given Arrayconst R = 3;const C = 6; // Function to form the spiral matrixfunction formSpiralMatrix(arr, mat){    let top = 0,    bottom = R - 1,    left = 0,    right = C - 1;     let index = 0;     while (1)    {                 if (left > right)            break;         // Print top row        for(let i = left; i <= right; i++)            mat[top][i] = arr[index++];                     top++;         if (top > bottom)            break;         // Print right column        for (let i = top; i <= bottom; i++)            mat[i][right] = arr[index++];        right--;         if (left > right)            break;         // print bottom row        for (let i = right; i >= left; i--)            mat[bottom][i] = arr[index++];                     bottom--;         if (top > bottom)            break;         // Print left column        for(let i = bottom; i >= top; i--)            mat[i][left] = arr[index++];                     left++;    }} // Function to print the spiral matrixfunction printSpiralMatrix(mat){    for(let i = 0; i < R; i++)    {        for(let j = 0; j < C; j++)            document.write(mat[i][j] + " ");                     document.write("<br>");    }} // Driver codelet arr = [ 1, 2, 3, 4, 5, 6,            7, 8, 9, 10, 11, 12,            13, 14, 15, 16, 17, 18 ];             let mat = new Array(R);for(let i = 0; i < R; i++)    mat[i] = new Array(C); formSpiralMatrix(arr, mat);printSpiralMatrix(mat); // This code is contributed by subham348 </script>
1   2  3  4  5 6 
14 15 16 17 18 7 
13 12 11 10  9 8
 
kanugargng
29AjayKumar
princiraj1992
subham348
ankita_saini
spiral
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unique paths in a Grid with Obstacles
Traverse a given Matrix using Recursion
Find median in row wise sorted matrix
Zigzag (or diagonal) traversal of Matrix
A Boolean Matrix Question
Python program to add two Matrices
Find a specific pair in Matrix
Common elements in all rows of a given matrix
Find shortest safe route in a path with landmines
Flood fill Algorithm - how to implement fill() in paint?