Created
December 8, 2014 14:47
-
-
Save zbinlin/a65f8a0a103078a98118 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
/* | |
* spiral matrix | |
* 根据给出的行(row)与列(col),生成一个螺旋数组([[x0, y0], .., [x, y]]]) | |
* 如 row = 3, col = 4 | |
* 01, 02, 03, 04 | |
* 10, 11, 12, 05 | |
* 09, 08, 07, 06 | |
* 将生成: | |
* [[0, 0], [1, 0], [2, 0], [3, 0], [3, 1], [3, 2], [2, 2], [1, 2], [0, 2], [0, 1], [1, 1], [2, 1]] | |
* | |
* @param {Number} row | |
* row | |
* @param {Number} col | |
* column | |
* @param {Number} [max = Math.pow(2, 64)] | |
* 螺旋最大圈数 | |
* | |
* @return {Array} | |
* spiral array | |
*/ | |
function getSpiralArray(row, col, max) { | |
var arr = []; | |
max || (max = Math.pow(2, 64)); | |
for (var n = 0; 2 * n < row && 2 * n < col && n < max; n++) { | |
/* ltr */ | |
for (var x = n, y = n; x < col - n; x++) arr.push([x, y]); | |
/* utd */ | |
for (var x = col - 1 - n, y = n + 1; y < row - n && x > n; y++) arr.push([x, y]); | |
/* rtl */ | |
for (var x = col - 2 - n, y = row - 1 - n; x > n - 1 && y > n; x--) arr.push([x, y]); | |
/* dtu */ | |
for (var x = n, y = row - 2 - n; y > n; y--) arr.push([x, y]); | |
} | |
return arr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment