Loading

剑指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;
    }
  }
}
posted @ 2020-03-13 11:26  Jacob是我了  阅读(113)  评论(0编辑  收藏  举报