Vassil_Iliev

spiral matrix implement JS

Mar 26th, 2022
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function spiralMatrix(n) {
  2.     let matrix = [];
  3.  
  4.     for (let i = 0; i < n; i++) {
  5.         matrix[i] = [];
  6.     }
  7.  
  8.     let firstRow = 0;
  9.     let lastRow = n - 1;
  10.     let firstCol = 0;
  11.     let lastCol = n - 1;
  12.     let index = 1;
  13.  
  14.     while (firstRow <= lastRow && firstCol <= lastCol) {
  15.  
  16.         for (let i = firstCol; i <= lastCol; i++) {
  17.             matrix[i][firstRow] = index;
  18.             index++
  19.         }
  20.  
  21.         firstCol++;
  22.  
  23.         for (let i = firstCol; i <= lastCol; i++) {
  24.             matrix[lastRow][i] = index;
  25.             index++
  26.         }
  27.  
  28.         lastRow--;
  29.  
  30.         for (let i = lastRow; i >= firstRow; i--) {
  31.             matrix[i][lastCol] = index;
  32.             index++;
  33.         }
  34.  
  35.         lastCol--;
  36.  
  37.         for (let i = lastCol; i >= firstCol; i--) {
  38.             matrix[firstRow][i] = index;
  39.             index++
  40.         }
  41.  
  42.         firstRow++;
  43.     }
  44.     console.table(matrix)
  45. }
  46.  
  47. spiralMatrix(5)
Advertisement
Add Comment
Please, Sign In to add comment