Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Ram-1234/c76463fa2369a94a964e5924bac5e5da to your computer and use it in GitHub Desktop.
Save Ram-1234/c76463fa2369a94a964e5924bac5e5da to your computer and use it in GitHub Desktop.
SPIRAL ARRAY IN CLOCKWISE
specification:-
Given a matrix of m * n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example:-
Input
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
output
[1, 2, 3, 6, 9, 8, 7, 4, 5]
Explanation-
top-> 1 2 3 4
6 8 9 6
btm-> 2 4 3 5
^ ^
| |
lft rht
########################JAVA CODE######################################################################
public class Solution {
// DO NOT MODIFY THE ARGUMENTS WITH "final" PREFIX. IT IS READ ONLY
public int[] spiralOrder(final int[][] mat) {
int k=0;
int m=mat.length;
int n=mat[0].length;
if(m==1 && n==1)
return mat[0];
int arr[]=new int[m*n];
int top=0,btm=m-1,lft=0,rht=n-1,dir=0;
while(top<=btm && lft<=rht)
{
if (dir==0) //Move left to right
{
for(int i=top;i<=rht;i++)
{
arr[k++]=mat[top][i];
}
top=top+1;
dir=1;
}
else if(dir==1)//Move top to bottom
{
for(int i=top;i<=btm;i++)
{
arr[k++]=mat[i][rht];
}
rht=rht-1;
dir=2;
}
else if(dir==2)//move right to left
{
for(int i=rht;i>=lft;i--)
{
arr[k++]=mat[btm][i];
}
btm=btm-1;
dir=3;
}
else if(dir==3) ///move bottom to top
{
for(int i=btm;i>=top;i--)
{
arr[k++]=mat[i][lft];
}
lft=lft+1;
dir=0;
}
}
return arr;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment