Two Matrix Spiral Print

The program must accept two square matrices which are of size N*N. Then the values in the matrices must be printed spirally in clock wise direction in a single line. The values in a specific row or column of the first matrix must follow the values in the same row or column of the second matrix.
Boundary Condition(s):
1 <= N <= 30
1 <= Integer value in the matrix <= 1000
Input Format:
The first line contains N.
Next 2N lines contain N values each (First N lines contain the values in the first matrix and the next N lines contain the values in the second matrix).
Output Format:
The first line contains 2*N*N values in the two matrices printed spirally.
Example Input/Output 1:
Input:
5
10 20 30 40 50
60 70 80 90 91
88 86 34 35 36
21 22 23 24 25
71 72 73 74 75
101 102 103 104 105
106 107 108 109 110
111 112 113 114 115
116 117 118 119 120
121 122 123 124 125
Output:
10 20 30 40 50 101 102 103 104 105 91 36 25 75 110 115 120 125 74 73 72 71 124 123 122 121 21 88 60 116 111 106 70 80 90 107 108 109 35 24 114 119 23 22 118 117 86 112 34 113
Example Input/Output 2:
Input:
4
78 51 30 23
83 53 7 32
40 62 4 77
100 83 19 21
100 37 45 13
2 100 97 72
10 91 91 32
61 98 87 6
Output:
78 51 30 23 100 37 45 13 32 77 21 72 32 6 19 83 100 87 98 61 40 83 10 2 53 7 100 97 4 91 62 91

Solution :-
#include<stdio.h>
#include <stdlib.h>

int spiral(int m,int n,int arr1[n][n],int arr2[n][n])
{
    int i,k=0,l=0;
    while(k<m && l<n)
    {
        for(i=l;i<n;++i)
        {
            printf("%d ",arr1[k][i]);
        }
        for(i=l;i<n;++i)
        {
            printf("%d ",arr2[k][i]);
        }
        k++;
        
        for(i=k;i<m;++i)
        {
            printf("%d ",arr1[i][n-1]);
        }
        for(i=k;i<m;++i)
        {
            printf("%d ",arr2[i][n-1]);
        }
        n--;
        
        if(k<m)
        {
            for(i=n-1;i>=l;--i)
            {
                printf("%d ",arr1[m-1][i]);
            }
            for(i=n-1;i>=l;--i)
            {
                printf("%d ",arr2[m-1][i]);
            }
            m--;
        }
        
        if(l<n)
        {
            for(i=m-1;i>=k;--i)
            {
                printf("%d ",arr1[i][l]);
            }
            for(i=m-1;i>=k;--i)
            {
                printf("%d ",arr2[i][l]);
            }
            l++;
        }     
    }
}

int main()
{
    int n;
    scanf("%d",&n);
    int arr1[n][n],arr2[n][n];
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            scanf("%d",&arr1[i][j]);
        }
    } 
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            scanf("%d",&arr2[i][j]);
        }
    }
    spiral(n,n,arr1,arr2);  
    printf("   h   ");
    return 0;
}

Comments

Popular posts from this blog

Alphabets Positions Reversed

Odd Factors - (Error Identification) skillrack program id - 7306