Skip to content

Instantly share code, notes, and snippets.

@ShvedAction
Created December 1, 2019 10:49
Show Gist options
  • Save ShvedAction/3a084da73e98cfeb20a400947c0ec4d7 to your computer and use it in GitHub Desktop.
Save ShvedAction/3a084da73e98cfeb20a400947c0ec4d7 to your computer and use it in GitHub Desktop.
spiral matrix
var beetwen = function(point, bords){
let [x, y] = point
let [xmin, ymin, xmax, ymax] = bords
return xmin < x && x < xmax && ymin < y && y < ymax
}
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function(matrix, direction, start, rect) {
if (matrix.length == 0)
return []
let s = matrix.length * matrix[0].length
direction = direction ? direction : [1, 0]
start = start ? start : [0, 0]
rect = rect ? rect : [-1, -1, matrix[0].length, matrix.length]
let result = []
while(beetwen(start, rect)){
let [x, y] = start
result.push(matrix[y][x])
// let's go toward direction
start[0] = start[0] + direction[0]
start[1] = start[1] + direction[1]
}
// stop recursion if it was center
if (result.length == 0)
return result
// now we out of bounds
// go back by one step
start[0] = start[0] - direction[0]
start[1] = start[1] - direction[1]
// now we need to rotate direction on 90 degrees
let [xD, yD] = direction
direction = [-yD , xD]
// we need to reduce our bounds in this derection
// change borders for x
rect[0] = direction[0] > 0 ? rect[0] + 1 : rect[0]
rect[2] = direction[0] < 0 ? rect[2] - 1 : rect[2]
// change borders for y
rect[1] = direction[1] > 0 ? rect[1] + 1 : rect[1]
rect[3] = direction[1] < 0 ? rect[3] - 1 : rect[3]
// next start position should be on next side
start[0] = start[0] + direction[0]
start[1] = start[1] + direction[1]
// concatinate with child results
return result.concat(spiralOrder(matrix, direction, start, rect))
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment