Print a given matrix in spiral form
Given a 2D array, print it in spiral form. See the following examples.
Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Output: 1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11
https://www.youtube.com/watch?v=siKFOI8PNKM&feature=youtu.be
Solution in Java
public class Solution {
// DO NOT MODIFY THE LIST
public ArrayList<Integer> spiralOrder(final List<ArrayList<Integer>> a) {
//Initialization of 4 pointers top bottom left and right
int top = 0,bottom = a.size()-1,left = 0,right = a.get(0).size()-1;
// below variable will control the direction
int direction = 0;
ArrayList<Integer> res = new ArrayList<Integer>();
// the while loop will execute until the top meets bottom and left meets right
while(bottom>=top && right>=left)
{
if(direction==0)
{
for(int i =left;i<=right;i++)
{
res.add(a.get(top).get(i));
}
top++;
}
else if(direction==1)
{
for(int i =top;i<=bottom;i++)
{
res.add(a.get(i).get(right));
}
right--;
}
else if(direction==2)
{
for(int i=right;i>=left;i--)
{
res.add(a.get(bottom).get(i));
}
bottom--;
}
else if(direction==3)
{
for(int i =bottom;i>=top;i--)
{
res.add(a.get(i).get(left));
}
left++;
}
//this helps to put back the direction to 0 so that we are again pointed to the top row of the
//matrix
direction = (direction+1)%4;
}
return res;
}
}
No comments:
Post a Comment