JavaScript definition and output spiral matrix method

This example describes the method of JavaScript definition and output spiral matrix. Share to everyone for your reference, as follows:

Inadvertently saw such an algorithm topic, then think about JS.
After the grass was written, it was very ugly, very stinking, so tonight, it felt elegant.

What is a spiral matrix The spiral matrix refers to a matrix with a spiral shape, and its number is started to the right of the first row, and downward Big, becomes large, and the upwards are large, so loop.

Realization

JavaScript定义及输出螺旋矩阵的方法详解

Implementation code

JavaScript定义及输出螺旋矩阵的方法详解

(Function () {VAR MAP = (function () {function map (n) {this.map = [], this.row = 0, this.col = -1, this.dir = 0, this.n = n; // Established a two-dimensional array for (VAR i = 0; i

 more relevant content on JavaScript interested readers can view the site topic: "JavaScript math usage summary", "JavaScript data structures and algorithms skills summary", "JavaScript array manipulation skills summary", "JavaScript event-related operations and techniques Daquan, "JavaScript Operation DOM Skill Summary" and "JavaScript Character and String Operation Skill Summary"  < 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();
})();

 I hope this article will help you JavaScript programming. 
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment