Print Array Diagonally
Explanation :
Here we will use two loops first to print diagonally until row<n
Second we will track all the values which remains i.e. from row=n-1 and col =1 and will print them diagonally in the upper direction manner.
Here we are going bottom to top so i am using stack so that we can have reverse the order as it is being asked in problem.
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
int n=ab.nextInt();
int arr[][]=new int[n][n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
arr[i][j]=ab.nextInt();
int i;
for(i=0;i<n;i++)
{
int j=-1;
int temp=i+1;
if(i==0 && j==-1)
{
System.out.print(arr[i][++j]+" ");
continue;
}
Stack<Integer> stk=new Stack<Integer>();
while(++j<n && --temp>=0)
{
stk.push(arr[temp][j]);
}
while(stk.empty()!=true)
{
System.out.print(stk.pop()+" ");
}
}
for(i=1;i<n;i++)
{
int j=n;
Stack<Integer> stk=new Stack<Integer>();
int temp=i-1;
while(--j>=0 && ++temp<n)
stk.push(arr[j][temp]);
while(stk.empty()!=true)
{
System.out.print(stk.pop()+" ");
}
}
System.out.print("\n");
}
}
}
0 Comments:
Post a Comment