Spiral Matrix — Problem solution
Day 8 — 100DaysCodingChallenge
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).
Directions: 0 - right, 1- down, 2-left, and 3-up.
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<>();
The loop will continue for each and every item in the matrix as long as the value of index i and j are valid and m[i][j] is not doom.
while (i >= 0 && j >= 0 && i < M && j < N && m[i][j] != doom) {
The initial direction will be right as it was set to 0 while initialized and it’ll be updated to continue as a spiral (right > down > left > up).
Based on the current direction, the inner while loop will read all the following items from the matrix in the same row or the column as long as there are items to be read and the item isn’t doom.
After each inner while loop, the value of i or j will be one block ahead (based on the direction). Bring that block down, increment one block in the next direction and change the direction to the next direction.
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)
Space Complexity: O(m*n)