A friend was in need of an algorithm that would let him loop through the elements of an NxM matrix (N and M are odd). I came up with a solution, but I wanted to see if my fellow SO'ers could come up with a better solution.

I'm posting my solution as an answer to this question.

**Example Output:**

For a 3×3 matrix, the output should be:

(0, 0)

(1, 0)

(1, 1)

(0, 1)

(-1, 1)

(-1, 0)

(-1, -1)

(0, -1)

(1, -1)

Furthermore, the algorithm should support non-square matrices, so for example for a 5×3 matrix, the output should be:

(0, 0)

(1, 0)

(1, 1)

(0, 1)

(-1, 1)

(-1, 0)

(-1, -1)

(0, -1)

(1, -1)

(2, -1)

(2, 0)

(2, 1)

(-2, 1)

(-2, 0)

(-2, -1)

## Best Solution

Here's my solution (in Python):