Wipro Coding Question 6
Matrix Traversal
Matrix Traversal is one of the coding question asked in previous wipro Elite NTH Exam. In this article, we will discuss about the Matrix Traversal problem with their solution in C++ and Java.
Question 6
Given an integer matrix of size N x N. Traverse it in a spiral form.
Format:
Input:
The first line contains N, which represents the number of rows and columns of a matrix. The next N lines contain N values, each representing the values of the matrix.
Output:
A single line containing integers with space, representing the desired traversal.
- Constraints: 0 < N < 500
Example 1:
Input:
3
1 2 3
4 5 6
7 8 9
Output:
1 2 3 6 9 8 7 4 5
Example 2:
Input
3
1 2 3
4 5 6
7 8 9
Output:
1 2 3 6 9 8 7 4 5
Java
C++
Java
import java.util.*;
class Main
{
public static void spiral (int arr[][], int row, int col)
{
int i, k = 0, l = 0;
while (k < row && l < col)
{
for (i = l; i < col; ++i)
System.out.print (arr[k][i] + " ");
k++;
for (i = k; i < row; ++i)
System.out.print (arr[i][col - 1] + " ");
col--;
if (k < row)
{
for (i = col - 1; i >= l; --i)
System.out.print (arr[row - 1][i] + " ");
row--;
}
if (l < col)
{
for (i = row - 1; i >= k; --i)
System.out.print (arr[i][l] + " ");
l++;
}
}
}
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
int n = sc.nextInt ();
int arr[][] = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
arr[i][j] = sc.nextInt ();
spiral (arr, arr.length, arr[0].length);
}
}
C++
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
int a[n][n], col=n, row=n;
for(int i=0; i<n; i++){
for(int j=0; j<n; j++)
cin>>a[i][j];
}
int k = 0, l = 0;
while (k < row and l < col){
for (int i = l; i < col; i++)
cout<<a[k][i]<<" ";
k++;
for (int i = k; i < row; i++)
cout<<a[i][n - 1]<<" ";
col--;
if (k < row){
for (int i = col - 1; i >= l; i--)
cout<<a[n - 1][i]<<" ";
row--;
}
if (l < col){
for (int i = row - 1; i >= k; --i)
cout<<a[i][l]<<" ";
l++;
}
}
return 0;
}
f=[]
l = [
[12,7],
[4 ,5]]
l3=l.copy()
for h in range(0,len(l)//2):
l1=[]
final=[]
final=final+l[0]
for i in range(0,len(l)):
if(i==0) or (i==len(l)-1):
pass
else:
final.append(l[i][-1])
final=final+l[-1][::-1]
for i in range(0,len(l)):
if(i==0) or (i==len(l)-1):
pass
else:
l1.append(l[i][0])
final=final+l1[::-1]
f=f+final
for i in range(0,len(l)):
l[i].pop(0)
l[i].pop(-1)
l.pop(0)
l.pop(-1)
print(l)
if(len(l3)%2!=0):
f=f+l[0]
print(f)