# 题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字

提示

  • 0 <= matrix.length <= 100
  • 0 <= matrix[i].length <= 100

# 测试用例

用例1:

  • 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
  • 输出:[1,2,3,6,9,8,7,4,5]

用例2:

  • 输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
  • 输出:[1,2,3,4,8,12,11,10,9,5,6,7]

# 思路

模拟顺时针的顺序,但是分为矩形的四条边来操作

1

注意下边的那条边和左边的那条边需要判断是否存在这条边,因为如果输入矩阵是[1,2],则只需要遍历上边和右边就可以了

# 代码实现

/**
 * @param {number[][]} matrix
 * @return {number[]}
 */

// 输入

var __readline = require("readline-sync");
__readline.setDefaultOptions({ prompt: "" });
var readline = __readline.prompt;

console.log("请输入矩阵的行数row: ");
const row = Number(readline());

console.log("请按行输入矩阵: ");
const matrix = [];
for (let i = 0; i < row; i++) {
  const arr = readline().split(",").map(Number);
  matrix.push(arr);
}

var spiralOrder = function (matrix) {
  if (!matrix.length || !matrix[0].length) {
    return [];
  }

  // 几行
  const rows = matrix.length;
  // 几列
  const columns = matrix[0].length;

  // 存储结果
  const ans = [];

  // 初始化遍历区间
  let left = 0,
    right = columns - 1,
    top = 0,
    bottom = rows - 1;
  while (left <= right && top <= bottom) {
    // x模拟行移动
    // y模拟列移动
    // 左上到右上 —— 列操作
    for (let y = left; y <= right; y++) {
      ans.push(matrix[top][y]);
    }

    // 右上到左下 —— 行操作
    for (let x = top + 1; x <= bottom; x++) {
      ans.push(matrix[x][right]);
    }
    // 判断是否要回头遍历
    if (left < right && top < bottom) {
      // 右下到左下 —— 列操作
      for (let y = right - 1; y > left; y--) {
        ans.push(matrix[bottom][y]);
      }
      // 左下到左上 —— 行操作
      for (let x = bottom; x > top; x--) {
        ans.push(matrix[x][left]);
      }
    }
    [left, right, top, bottom] = [left + 1, right - 1, top + 1, bottom - 1];
  }
  return ans;
};

console.log("结果为: ", spiralOrder(matrix));

/* 
  请输入矩阵的行数row:
  3
  请按行输入矩阵:
  1,2,3
  4,5,6
  7,8,9
  结果为:  [
    1, 2, 3, 6, 9,
    8, 7, 4, 5
  ]
*/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82