Spiral Matrix — Problem solution

Problem:

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

m == matrix.length
n == matrix[i].length
1 <= 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[0].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)

Find Me On:

Instagram, GitHub, LinkedIn, Twitter.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store