螺旋矩阵
螺旋矩阵指一个呈螺旋状的矩阵,其数字由第一行开始到右边不断变大,向下变大,向左变大,向上变大, 如此循环。
实例代码如下:
1 (function() { 2 var map = (function() { 3 4 function map(n) { 5 this.map = [], 6 this.row = 0, 7 this.col = -1, 8 this.dir = 0, 9 this.n = n; 10 11 // 建立一个二维数组,在一维数组基础上动态增加,取决于n的大小 12 for (var i = 0; i < this.n; i++) { 13 this.map.push([]); 14 } 15 16 // 定义移动的顺序为:右,下,左,上 17 var order = [this.right, this.bottom, this.left, this.up]; 18 i = 0; 19 do { 20 order[this.dir % 4].call(this) ? i++ : this.dir++; 21 this.map[this.row][this.col] = i; 22 } while (i < n * n); 23 } 24 25 map.prototype = { 26 println: function() { 27 for (var i = 0; i < this.n; i++) { 28 console.log(this.map[i].join(' ')) 29 } 30 }, 31 left: function() { 32 return this.move(this.row, this.col - 1); 33 }, 34 right: function() { 35 return this.move(this.row, this.col + 1); 36 }, 37 up: function() { 38 return this.move(this.row - 1, this.col); 39 }, 40 bottom: function() { 41 return this.move(this.row + 1, this.col); 42 }, 43 move: function(row, col) { 44 return (0 <= row && row < this.n) && (0 <= col && col < this.n) && !this.map[row][col] && (this.row = row, this.col = col, true); 45 }, 46 }; 47 48 return map; 49 })(); 50 51 new map(3).println(); 52 // 改变map的参数值,能得到不同结果 53 54 })();
图例:
(1)执行上述代码得
(2)改变第51行为:new map(6).println();