Detailed description of JavaScript definition and output spiral matrix, javascript Matrix
This document describes how to define and output a spiral matrix using JavaScript. We will share this with you for your reference. The details are as follows:
I did not intend to see such an algorithm question last night, and then I thought about using js to implement it.
After the rough grass was written last night, I felt the code was ugly and smelly. So I spent some time restructuring it tonight and it became elegant.
What is a spiral matrix?
A spiral matrix refers to a spiral matrix. Its numbers grow from the first row to the right, and become larger downward, larger to the left, and larger up.
Effect
Implementation Code
(Function () {var map = (function () {function map (n) {this. map = [], this. row = 0, this. col =-1, this. dir = 0, this. n = n; // create a two-dimensional array for (var I = 0; I <this. n; I ++) {this. map. push ([]);} // defines the moving order as right, bottom, left, and upper var order = [this. right, this. bottom, this. left, this. up]; I = 0; do {// The number is updated if it can be moved; otherwise, the order [this. dir % 4]. call (this )? I ++: this. dir ++; // value 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 ('') }}, // move 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) ;}, botto M: function () {return this. move (this. row + 1, this. col) ;}, // If the coordinate is within the range and the target has no value, update the coordinate move: function (row, col) if the condition is met) {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 ();})();