logo CodeStepByStep logo

spiral

Write a method named spiral that accepts a 2-D array of integers as a parameter and that returns a 1-D array with the contents of the original 2-D array in the order they would appear if visited in a "spiral" order, clockwise starting from top-left. For example, if the given 2-D array is declared:

int[][] matrix = {
    { 1,  2,  3,  4,  5},
    { 6,  7,  8,  9, 10},
    {11, 12, 13, 14, 15},
    {16, 17, 18, 19, 20},
};

Then the call of spiral(matrix) should return the following 1-D array:

{1, 2, 3, 4, 5, 10, 15, 20, 19, 18, 17, 16, 11, 6, 7, 8, 9, 14, 13, 12}

You may assume that the 2-D array is rectangular, that is, that each row of the 2-D array contains the same number of columns. You may also assume that the 2-D array contains at least one row and column. Your method should not modify the array that is passed in.

Method: Write a Java method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.