Good morning everybody, i'm trying to write a method that given a N number will create a spiral matrix with size of N*N, the method below works just fine but the execution time of the code is about 2s when it should be around few ms, i don't know what actually makes the code so slow, can you help me figure it out?, thanks.
I wrote another method that called this one (spirale) with different numbers in the following order and had the following results.
test1: n=10 execution time-> 2475ms
test2: n=5 execution time-> 7795ms
test3: n=1 execution time-> 7169ms
test4: n=0 execution time-> 7034ms
test5: n=6 execution time-> 7056ms
public static int[][] spirale(int N){
int i=0, j=0, giro = 0, numbers = 1;
int mat[][] = new int[N][N];
while(true){
for(j=0+giro; j<N-giro; j++){
if(numbers>N*N) return mat;
mat[i][j] = numbers++;
}
j--;
for(i=1+giro; i<N-giro ; i++){
if(numbers>N*N) return mat;
mat[i][j] = numbers++;
}
i--;
for(j=N-2-giro; j>=0+giro; j--){
if(numbers>N*N) return mat;
mat[i][j] = numbers++;
}
j++;
for(i=N-2-giro ; i>0+giro ; i--){
if(numbers>N*N) return mat;
mat[i][j] = numbers++;
}
i++;
giro++;
}
}