1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
var generateMatrix = function(n) { let result = [] let num = 1; let rowStart = 0; let cloumnStart = 0; let rowEnd = n-1; let cloumnEnd = n-1; let power = Math.pow(n,2) for(let i =0;i<n;i++){ result.push([]) } while(num <= power){ for(let i = cloumnStart;i<=cloumnEnd;i++){ result[rowStart][i] = num++ } rowStart++ for(let i = rowStart;i<=rowEnd;i++){ result[i][cloumnEnd] = num++ } cloumnEnd-- for(let i = cloumnEnd;i>=cloumnStart;i--){ result[rowEnd][i] = num++ } rowEnd-- for(let i = rowEnd;i>=rowStart;i--){ result[i][cloumnStart] = num++ } cloumnStart++ } return result };
|