Created
December 1, 2019 10:49
-
-
Save ShvedAction/3a084da73e98cfeb20a400947c0ec4d7 to your computer and use it in GitHub Desktop.
spiral matrix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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