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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

涛锅   2020-05-16 我要评论

本文实例讲述了JavaScript定义及输出螺旋矩阵的方法。分享给大家供大家参考,具体如下:

昨晚无意看到这样一个算法题目,然后就想着用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();
})();

希望本文所述对大家JavaScript程序设计有所帮助。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们