zoukankan      html  css  js  c++  java
  • 剑指offer[19]——顺时针打印矩阵

    题目描述

    输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

    顺时针打印矩阵图示如下:
    image-20200313105458416

    大家仔细观察一下这张图,当箭头在向右走的时候走不动了,只能向下走;向下走走不动的时候,只能向左走;向左走走不动的时候,只能向上走;向上走走不动的时候,只能向右走。

    明白了这个大家应该就可以明白怎么做了,使用switch语句,分别判断箭头在向上下左右四个方向走的情况,每走过一个方格,就将其值变为#

    以向右走为例,只要当前位置的右边不为#并且没有越界,那么就可以一直向右走,反之,只要这两个条件有一个没有满足,就要向下走。

    function printMatrix(matrix) {
      if (!matrix.length) {
        return [];
      }
      const length = matrix[0].length;
      const width = matrix.length;
      let x = 0;
      let y = 0;
      let res = [];
      let direction = 'right';
      while (true) {
        res.push(matrix[x][y]);
        matrix[x][y] = '#';
        switch (direction) {
          case 'right':
            if (y + 1 < length && matrix[x][y + 1] != '#') { y++; }
            else if (x + 1 < width && matrix[x + 1][y] != '#') { x++; direction = 'down' }
            else{ return res; }
            break;
          case 'left':
            if (y - 1 >= 0 && matrix[x][y - 1] != '#') { y--; }
            else if (x - 1 >= 0 && matrix[x - 1][y] != '#') { x--; direction = 'up' }
            else{ return res; }
            break;
          case 'up':
            if (x - 1 >= 0 && matrix[x - 1][y] != '#') { x--; }
            else if (y + 1 < length && matrix[x][y + 1] != '#') { y++; direction = 'right' }
            else{ return res; }
            break;
          case 'down':
            if (x + 1 < width && matrix[x + 1][y] != '#') { x++; }
            else if (y - 1 >= 0 && matrix[x][y - 1] != '#') { y--; direction = 'left' }
            else{ return res; }
            break;
        }
      }
    }
    
  • 相关阅读:
    localstorage和sessionstorage的区别
    vue监听数组变化
    博客项目之设计访客统计
    记录从前端到后端--博客项目
    把w3schools英文版的所有属性扒下来了,免费分享。
    记一次博客园改版,如果你想做的漂亮点的话。
    我有话说
    彻底理解nth-child和nth-of-type的区别。
    前端这条路,我们该何去何从,续集
    一篇通俗易懂的CSS层叠顺序与层叠上下文研究
  • 原文地址:https://www.cnblogs.com/Jacob98/p/12485276.html
Copyright © 2011-2022 走看看