Sunday, April 1, 2012

GIven a 2D NxN matrix, visualize it as concentric circles. You have to find the rotated matrix where each element in the circle is rotated by 1 position layer by layer in an alternate clockwise and anticlockwise direction.


For Example 
Input:
4
2 3 4 5
1 6 7 8
4 2 1 9
5 3 2 4

Output:
1 2 3 4 
4 7 1 5 
5 6 2 8 
3 2 4 9 

2 comments :

vikky said...

/**
*
* @author Vikky
*/

import java.util.*;

public class CircularLoop {
int dimension=0;
int arr[][];

public static void main(String args[])
{
CircularLoop obj=new CircularLoop();
obj.arr=new int[5][5];
int temp=1;
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
obj.arr[i][j]=temp++;
}
}
//obj.print(obj.arr);
for(int i=0;i<5;i++)
{
obj.store(i, 5);
}


}


void store(int i,int len)
{

ArrayList ar=new ArrayList();
int temp=0;
for(int k=i;k=i;k--)
{
ar.add(arr[len-i-1][k]);
}

for(int k=len-i-2;k>i;k--)
{
ar.add(arr[k][i]);
}
this.print1(ar);


if(i%2==0)
this.cw(ar);
else
this.acw(ar);

}

void print(int [][]arr)
{
System.out.println("");
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
System.out.println(arr[i][j]);
}
}
}

void print1(ArrayList ar)
{
System.out.println("");
Iterator ir=ar.iterator();
while(ir.hasNext())
{
System.out.print(ir.next()+" ");

}
}

void acw(ArrayList ar)
{
if(ar.size()>0)
{
int size=ar.size();
ArrayList aa=new ArrayList();
aa.add(ar.get(size-1));
for(int i=0;i ar)
{
if(ar.size()>0)
{
int size=ar.size();
ArrayList aa=new ArrayList();
aa.add(0, ar.get(size-1));
for(int i=0;i<size-1;i++)
aa.add(ar.get(i));

System.out.println("\nClockwise :");
this.print1(aa);
}
}


}

Anonymous said...

@Vikky

can you give more insight by giving algo ?