Q:-Given a matrix of size N x N. Print the elements of the matrix in the snake like pattern depicted below.
Example 1:
Input:
N = 3
matrix[][] = {{45, 48, 54},
{21, 89, 87}
{70, 78, 15}}
Output:
45 48 54 87 89 21 70 78 15
Explanation:
Matrix is as below:
45 48 54
21 89 87
70 78 15
Printing it in snake pattern will lead to
the output as 45 48 54 87 89 21 70 78 15.
Example 2:
Input:
N = 2
matrix[][] = {{1, 2},
{3, 4}}
Output:
1 2 4 3
Explanation:
Matrix is as below:
1 2
3 4
Printing it in snake pattern will
give output as 1 2 4 3.
Your Task:
You dont need to read input or print anything. Complete the function snakePattern() that takes matrix as input parameter and returns a list of integers in order of the values visited in the snake pattern.
Expected Time Complexity: O(N * N)
Expected Auxiliary Space: O(N * N) for the resultant list only.
Constraints:
1 <= N <= 103
1 <= mat[i][j] <= 109
Solution:-
//{ Driver Code Starts
//Initial Template for C
#include <stdio.h>
// } Driver Code Ends
//User function Template for C
//Function to return list of integers visited in snake pattern in matrix.
int* snakePattern(int n, int matrix[][n])
{
int i,j,k,x,t[n];
for(i=0;i<n;i++)
{
if((i%2)==0)
{
for(j=0;j<n;j++)
{
matrix[i][j] =matrix[i][j];
}
}
else
{ x=0;
for(k=n-1;k>=0;k--)
{
t[x] =matrix[i][k];
x++;
}
for(j=0;j<n;j++)
{
matrix[i][j]=t[j];
}
}
}
return matrix;
}
//{ Driver Code Starts.
int main()
{
int tc;
scanf("%d", &tc);
while(tc--){
int n;
scanf("%d", &n);
int matrix[n][n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
scanf("%d", &matrix[i][j]);
}
}
int *result = snakePattern(n, matrix);
for(int i = 0; i < n*n; i++)
printf("%d ", result[i]);
printf("\n");
}
return 0;
}
// } Driver Code Ends
No comments:
Post a Comment
HAY THAKYOU FOE VISIT