Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.3 kB
0
Indexable
Never
public class Solution {
    public ArrayList<ArrayList<Integer>> generateMatrix(int A) {
        ArrayList<ArrayList<Integer>> spiralMatrix = new ArrayList<ArrayList<Integer>>();
        for(int i=0;i<A;i++) {
            spiralMatrix.add(new ArrayList<Integer>());
            for(int j=0;j<A;j++) {
                spiralMatrix.get(i).add(0);
            }   
        }
        if(A == 0) {
            return spiralMatrix;
        }
        int r=0, c=0,number=1;
        while(A>1) {
            for(int k=0;k<A-1;k++) {
                spiralMatrix.get(r).set(c,number);
                number++;
                c++;
            }

            for(int k=0;k<A-1;k++) {
                spiralMatrix.get(r).set(c,number);
                number++;
                r++;
            }
            
            for(int k=0;k<A-1;k++) {
                spiralMatrix.get(r).set(c,number);
                number++;
                c--;
            }
            
            for(int k=0;k<A-1;k++) {
                spiralMatrix.get(r).set(c,number);
                number++;
                r--;
            }
            A = A-2;
            c++;
            r++;
        }
        if(A==1) {
            spiralMatrix.get(r).set(c,number);
        }
        return spiralMatrix;
    }
}