tdel
tdel

Reputation: 1009

Creating a Spiral Order Matrix using ArrayList of ArrayList

I am trying to generate Spiral Matrix given this problem : Given an integer n, generate a square matrix filled with elements from 1 to n squared, in spiral order. For example, given n = 4,

I am trying to have a return type of ArrayList to generate the matrix.

My problem is, everytime it starts to generate, it is updating the whole matrix not per row per colum, ending up to have the same value for each row and column.

Here is my code:

public static ArrayList<ArrayList<Integer>> generateMatrix(int a) {
    ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();

    //to create place holder for each element at the start - 0
    ArrayList<Integer> zero = new ArrayList<Integer>();
    for (int i=0; i<a; i++) {
        zero.add(0);
    }
    for (int i=0; i<a; i++) {
        res.add(zero);
    }

    int numToAdd = 1;
    int top = 0;
    int bottom = a-1;
    int left = 0;
    int right = a-1;


    while (numToAdd <= a*a) {
        for (int i = left; i<= right; i++) {
            res.get(top).set(i, numToAdd);
            numToAdd++;
        }
        top++;

        for (int i = top; i <= bottom; i++) {
            res.get(i).set(right, numToAdd);
            numToAdd++;
        }
        right--;

        for (int i=right; i>=left; i--) {
            res.get(bottom).set(i, numToAdd);
            numToAdd++;
        }
        bottom--;

        for(int i=bottom; i>= top; i--) {
            res.get(i).set(left, numToAdd);
            numToAdd++;
        }
        left++;
    }

    return res;
}

Upvotes: 1

Views: 987

Answers (1)

Jason C
Jason C

Reputation: 40315

Your problem is here:

//to create place holder for each element at the start - 0
ArrayList<Integer> zero = new ArrayList<Integer>();
...
for (int i=0; i<a; i++) {
    res.add(zero);
}

Basically, you've only created a single new "row" ArrayList, then you've added that same ArrayList a times to res. That means every res.get(n) just refers back to the same ArrayList instance. That is, all of your "rows" end up being the exact same ArrayList.

You'll want to instantiate a new ArrayList for each row instead, for example:

for (int i=0; i<a; i++) {
    // for each row make a *new* arraylist
    ArrayList<Integer> zero = new ArrayList<Integer>();
    // initialize that arraylist
    for (int j=0; j<a; j++) {
        zero.add(0);
    }
    // then add it to the row
    res.add(zero);
}

Upvotes: 2

Related Questions