用JavaScript实现螺旋矩阵算法
时间:2010-09-20 来源:George Wing
在实际开发中需要用到螺旋矩阵算法,用JS代码实现了:
var cal = function(len){ var helix = [[],[],[],[],[],[]]; var min = 0; var max = len - 1; var row = 0; var col = 0; for(var i=0; i < len * len; i++) { helix[row][col]=i+1; if(row == min && col < max) { col = col + 1; } else if(row < max && col == max) { row = row + 1; } else if(row == max && col > min) { col = col - 1; } else if(row > min && col == min) { row = row - 1; } if(row - 1 == min && col == min){ min = min + 1; max = max - 1; } } return helix; }; var helix = cal(6); var html = ''; for(var i=0; i < helix.length; i++) { for(var j=0; j < helix[i].length; j++) { html += helix[i][j] + ' '; } html += '<br />'; } $('#container').html(html);
相关阅读 更多 +