# LeetCode Spiral Matrix I and II: Recursive and Iterative Index Calculation

## Overview

LeetCode Spiral Matrix I and II is to test array index manipulation which can be done in both recursive and iterative manner to find the pattern of calculation

## LeetCode Spiral Matrix I and II

(1)

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

(2)

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:

[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

## Analysis: Recursive and Iterative Index Calculation

Basically, this problem could be solved by bother recursive and iterative algorithm, just directly simulate the spiral pattern: top->right->bottom->left. And the following recursive implementation for Spiral Matrix I is accepted by LeetCode OJ:

For the Spiral Matrix II, both of the following recursive and iterative implementation are accepted:

And the following is the iterative one:

Further Reference: “Printing Matrix (2D array) in Spiral Order“.

## Summary

LeetCode Spiral Matrix I and II is to test array index manipulation which can be done in both recursive and iterative manner to find the pattern of calculation

Written on May 9, 2013