# Problem:

Given an `m x n` `matrix`, return all elements of the `matrix` in spiral order.

`m == matrix.lengthn == matrix[i].length1 <= m, n <= 10-100 <= matrix[i][j] <= 100`

# Solution:

Defining all the variables required for the solution. The variable direction defines the direction in which the loop will continue and the variable doom could be any invalid integer number (<-100 or >100).

`class Solution {    public List<Integer> spiralOrder(int[][] m) {        int direction = 0, i = 0, j = 0;        int M = m.length, N = m.length, doom = 1000;        List<Integer> out = new ArrayList<>();`
`while (i >= 0 && j >= 0 && i < M && j < N && m[i][j] != doom) {`
`            switch (direction) {                case 0:                    while (j < N && m[i][j] != doom) {                        out.add(m[i][j]);                        m[i][j] = doom;                        j++;                    }                    j--; i++; direction = 1;                    break;                case 1:                    while (i < M && m[i][j] != doom) {                        out.add(m[i][j]);                        m[i][j] = doom;                        i++;                    }                    i--; j--; direction = 2;                    break;                case 2:                    while (j >= 0 && m[i][j] != doom) {                        out.add(m[i][j]);                        m[i][j] = doom;                        j--;                    }                    j++; i--; direction = 3;                    break;                case 3:                default:                    while (i >= 0 && m[i][j] != doom) {                        out.add(m[i][j]);                        m[i][j] = doom;                        i--;                    }                    i++; j++; direction = 0;                    break;            }        }        return out;    }}`

# Complexity:

Time Complexity: O(m*n)

--

--