Skip to content

Instantly share code, notes, and snippets.

@tahashieenavaz
Last active January 31, 2024 00:37
Show Gist options
  • Save tahashieenavaz/a51c1578305d2355efd58cc74e268bbd to your computer and use it in GitHub Desktop.
Save tahashieenavaz/a51c1578305d2355efd58cc74e268bbd to your computer and use it in GitHub Desktop.
Given an m x n matrix, return all elements of the matrix in spiral order.
/**
* @param {number[][]} matrix
* @return {number[]}
* https://underdash.web.app
* https://leetcode.com/problems/spiral-matrix/
* https://underdash.tech/spiral-matrix/
* Copyright reserved by Taha Shieenavaz (Underdash)
*/
const spiralOrder = matrix => {
const { abs } = Math
const rows = matrix.length, cols = matrix[0].length
const map = Array(rows).fill().map(row => {
return Array(cols).fill(false)
})
const result = []
const direction = { x: 1, y: 0 }
let i = 0, j = 0
while( map.flat().filter( a => !a ).length > 0 ) {
if(
( direction.x == -1 && i == 0 ) ||
( direction.y == -1 && j == 0 ) ||
( direction.x == 1 && i == cols - 1 ) ||
( direction.y == 1 && j == rows - 1 ) ||
map[j+direction.y][i+direction.x]
){
if( abs(direction.x) ) {
direction.y = direction.x
direction.x = 0
}else if( abs(direction.y) ) {
direction.x = -1 * direction.y
direction.y = 0
}
}
result.push(matrix[j][i])
map[j][i] = true
i += direction.x
j += direction.y
}
return result
};
@tahashieenavaz
Copy link
Author

tahashieenavaz commented Mar 24, 2022

Read more about this solution: https://underdash.pro/spiral-matrix/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment