Form a Spiral Matrix from the given Array

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 matrix
void 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 matrix
void 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 code
int 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to form a Spiral Matrix 
// from the given Array 
class 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to form a Spiral Matrix 
# from the given Array 
  
R = 3 ;
C = 6
  
# Function to form the spiral matrix 
def formSpiralMatrix(arr, mat):
    top = 0;
    bottom = R - 1;
    left = 0
    right = C - 1
  
    index = 0
  
    while (True):
          
        if(left > right): 
            break
  
        # prtop row 
        for i in range(left, right + 1):
            mat[top][i] = arr[index];
            index += 1;
        top += 1
  
        if (top > bottom):
            break
  
        # prright column 
        for i in range(top, bottom+1):
            mat[i][right] = arr[index];
            index += 1;
        right -= 1
  
        if (left > right):
            break
  
        # prbottom row 
        for i in range(right, left-1, -1):
            mat[bottom][i] = arr[index];
            index += 1;
        bottom -= 1
  
        if (top > bottom): 
            break
  
        # prleft column 
        for i in range(bottom, top-1, -1): 
            mat[i][left] = arr[index];
            index += 1;
        left += 1
# Function to prthe spiral matrix 
def printSpiralMatrix(mat):
    for i in range(R):
        for j in range(C):
            print(mat[i][j],end= " "); 
        print(); 
  
# Driver code 
if __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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to form a Spiral Matrix 
// from the given Array 
using 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

chevron_right


Output:

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.