码迷,mamicode.com
首页 > 其他好文 > 详细

[Algorithm] Print 2-D array in spiral order

时间:2019-03-28 09:39:58      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:The   nts   png   bsp   http   code   ide   ott   const   

技术图片

 

The idea to solve the problem is set five variable, first direction, we need to switch direction after we finish printing one row or one column.

dir = (dir+1) % 4

 

Then set four boundry, top, left, right, bottom:

  let results = [],
        dir = 0, //0: left -> right, 1: top -> bottom, 2: right -> left, 3: bottom -> top
        top = 0,
        bottom = arys.length - 1,
        left = 0,
        right = arys[0].length - 1;

Each time finish printing a row or a column, modify the boundry accordingly:

function PrintSpiralOrder (arys) {
  let results = [],
        dir = 0, //0: left -> right, 1: top -> bottom, 2: right -> left, 3: bottom -> top
        top = 0,
        bottom = arys.length - 1,
        left = 0,
        right = arys[0].length - 1;
  
  while (top <= bottom && left <= right) {
     if (dir === 0) {
       for (let i = left; i <= right; i++) {
         results.push(arys[top][i]);
       }
       top++;
     } else if (dir === 1) {
       for (let i = top; i <= bottom; i++) {
         results.push(arys[i][right]);
       }
       right--;
     } else if (dir === 2) {
       for (let i = right; i >= left; i--) {
         results.push(arys[bottom][i]);
       }
       bottom--;
     } else if (dir === 3) {
       for (let i = bottom; i >= top; i--) {
         results.push(arys[i][left]);
       }
       left++;
     }
    
     dir = (dir + 1) % 4;
  }
  
  return results;
}

const data = [
  [2,4,6,8],
  [5,9,12,16],
  [2,11,5,9],
  [3,2,1,8]
];

const res = PrintSpiralOrder(data);
console.log(res); // [ 2, 4, 6, 8, 16, 9, 8, 1, 2, 3, 2, 5, 9, 12, 5, 11 ]

 

[Algorithm] Print 2-D array in spiral order

标签:The   nts   png   bsp   http   code   ide   ott   const   

原文地址:https://www.cnblogs.com/Answer1215/p/10612493.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!