Advertisement
maymunskoa

07. Spiral Matrix (Arrays More Exercise)

Mar 10th, 2020
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(arg1,arg2){
  2.     let end = arg1*arg2;
  3.    
  4.     let matrix = [];
  5.     for(let i = 0; i < arg1; i++) {
  6.         matrix[i] = [];
  7.         for(let j = 0; j < arg2; j++){
  8.             matrix[i][j] = 0;
  9.         }
  10.     }
  11.  
  12.  
  13.     let stepRow = [0,1,0,-1];
  14.     let stepCol = [1,0,-1,0];
  15.     let indexChange = 0;
  16.     let index = indexChange%4;
  17.     let row = 0;
  18.     let col = 0;
  19.  
  20.  
  21.  
  22.     function isInvalid(){
  23.         if(row < 0 || row > arg1 - 1 || col < 0 || col > arg2 - 1){
  24.             return true;
  25.         }
  26.         if(row >=0 && row <= arg1 - 1 && col >= 0 && col <= arg2 - 1){
  27.             if(matrix[row][col] !== 0){
  28.                 return true;
  29.             }
  30.         }
  31.     }
  32.  
  33. for(let i = 1; i <= end; i++){
  34.     matrix[row][col] = i;
  35.     if(i === end){break;}
  36.     row += stepRow[index];
  37.     col += stepCol[index];
  38.     if(isInvalid()){
  39.         row -= stepRow[index];
  40.         col -= stepCol[index];
  41.         indexChange++;
  42.         index = indexChange%4;
  43.         row += stepRow[index];
  44.         col += stepCol[index];
  45.     }
  46. }
  47.  
  48.     console.log(matrix.map(r => r.join(' ')).join('\n'));
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement