Java easy to Understand solution using simple 2d arrays


#1

public class Solution {
public int[][] generateMatrix(int A) {
int dir =0;
int t = 0, b=A-1, l=0, r=A-1,c=1;
int[][] arr = new int[A][A];
while(t<=b && l<=r)
{
if(dir==0)
{
for(int i=l;i<=r;i++)
{
arr[t][i] = c;
c++;
}
t++;
dir=1;
}
else if(dir==1)
{
for(int i=t;i<=b;i++)
{
arr[i][r] = c;
c++;
}
r–;
dir=2;
}
else if(dir==2)
{
for(int i=r;i>=l;i–)
{
arr[b][i] = c;
c++;
}
b–;
dir=3;
}
else if(dir==3)
{
for(int i=b;i>=t;i–)
{
arr[i][l] = c;
c++;
}
l++;
dir=0;
}
}
return arr;

}

}