昨晚無意看到這樣一個算法題目,然后就想著用js來實現。
昨晚草草寫完后感覺代碼很丑,很臭,于是今晚又花點時間重構了一下,感覺變得優雅了。
什么是螺旋矩陣
螺旋矩陣是指一個呈螺旋狀的矩陣,它的數字由第一行開始到右邊不斷變大,向下變大,向左變大,向上變大,如此循環。
如圖:
實現效果
實現代碼
(function() { var map = (function() { function map(n) { this.map = [], this.row = 0, this.col = -1, this.dir = 0, this.n = n; // 建立個二維數組 for (var i = 0; i < this.n; i++) { this.map.push([]); } // 定義移動的順序為 右,下,左,上 var order = [this.right, this.bottom, this.left, this.up]; i = 0; do { // 能移動則更新數字,否則更改方向 order[this.dir % 4].call(this) ? i++ : this.dir++; // 賦值 this.map[this.row][this.col] = i; } while (i < n * n); } map.prototype = { print: function() { for (var i = 0; i < this.n; i++) { console.log(this.map[i].join(' ')) } }, // 向該方向移動 left: function() { return this.move(this.row, this.col - 1); }, right: function() { return this.move(this.row, this.col + 1); }, up: function() { return this.move(this.row - 1, this.col); }, bottom: function() { return this.move(this.row + 1, this.col); }, // 如果坐標在范圍內,并且目標沒有值,條件滿足則更新坐標 move: function(row, col) { return (0 <= row && row < this.n) && (0 <= col && col < this.n) && !this.map[row][col] && (this.row = row, this.col = col, true); }, }; return map; })(); new map(6).print(); })();
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com