昨晚無意看到這樣一個(gè)算法題目,然后就想著用js來實(shí)現(xiàn)。
昨晚草草寫完后感覺代碼很丑,很臭,于是今晚又花點(diǎn)時(shí)間重構(gòu)了一下,感覺變得優(yōu)雅了。
什么是螺旋矩陣
螺旋矩陣是指一個(gè)呈螺旋狀的矩陣,它的數(shù)字由第一行開始到右邊不斷變大,向下變大,向左變大,向上變大,如此循環(huán)。
如圖:
實(shí)現(xiàn)效果
實(shí)現(xiàn)代碼
(function() { var map = (function() { function map(n) { this.map = [], this.row = 0, this.col = -1, this.dir = 0, this.n = n; // 建立個(gè)二維數(shù)組 for (var i = 0; i < this.n; i++) { this.map.push([]); } // 定義移動的順序?yàn)?右,下,左,上 var order = [this.right, this.bottom, this.left, this.up]; i = 0; do { // 能移動則更新數(shù)字,否則更改方向 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); }, // 如果坐標(biāo)在范圍內(nèi),并且目標(biāo)沒有值,條件滿足則更新坐標(biāo) 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(); })();
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com