zoukankan      html  css  js  c++  java
  • JavaScript螺旋矩阵

       螺旋矩阵                                                                     

      螺旋矩阵指一个呈螺旋状的矩阵,其数字由第一行开始到右边不断变大,向下变大,向左变大,向上变大, 如此循环。

      实例代码如下:

     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();

        

     

  • 相关阅读:
    代码优化
    使用python的Flask实现一个RESTful API服务器端
    数据结构与算法之排序
    Ubuntu 13.04/12.10安装Oracle 11gR2图文教程(转)
    Linux 下开启ssh服务(转)
    PLSQL Developer 9.如何设置查询返回所有纪录(转)
    linux下安装oracle11g 64位最简客户端(转)
    Linux下关于解决JavaSwing中文乱码的情况(转)
    servlet(jsp)中的重定向和转发
    在用TabbarController中出现navigationController 嵌套报错
  • 原文地址:https://www.cnblogs.com/wuyongyu/p/5832198.html
Copyright © 2011-2022 走看看