Advertisement
Guest User

Spiral Matrix

a guest
Sep 21st, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function spiralMatrix(rows, cols) {
  2.     let matrix = [];
  3.     for (let i = 0; i < rows; i++) {
  4.         matrix.push('0'.repeat(cols).split('').map(Number));
  5.     }
  6.  
  7.     let num = 1;
  8.     let rowLength = matrix.length;
  9.     let colLength = matrix[0].length;
  10.     fillMatrix(0, 0);
  11.     printMatrix(matrix);
  12.  
  13.     function fillMatrix(startRow, startCol) {
  14.         if (matrix[startRow][startCol] !== 0) {
  15.             return;
  16.         }
  17.  
  18.         // fill Top
  19.         for(let col = startCol; col < colLength - startCol; col++) {
  20.             matrix[startRow][col] = num++;
  21.         }
  22.  
  23.         // fill Right
  24.         for(let row = 1 + startRow; row < rowLength - startRow; row++) {
  25.             matrix[row][colLength - 1 - startCol] = num++;
  26.         }
  27.  
  28.         // fill Bottom
  29.         for(let col = colLength - 2 - startCol; col >= startCol; col--) {
  30.             matrix[rowLength - 1 - startRow][col] = num++;
  31.         }
  32.  
  33.         // fill Left
  34.         for(let row = rowLength - 2 - startRow; row > startRow; row--) {
  35.             matrix[row][startCol] = num++;
  36.         }
  37.  
  38.         fillMatrix(++startRow, ++startCol);
  39.     }
  40.  
  41.     function printMatrix() {
  42.         console.log(matrix.map(el => el.join(" ")).join('\n'));
  43.     }
  44. }
  45.  
  46. spiralMatrix(10, 10);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement