跳至主要內容

54. 螺旋矩阵


54. 螺旋矩阵

🟠   🔖  数组 矩阵 模拟  🔗 力扣open in new window LeetCodeopen in new window

题目

Given an m x n matrix, return all elements of the matrix in spiral order.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]

Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]

Output: [1,2,3,4,8,12,11,10,9,5,6,7]

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

题目大意

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

解题思路

  • 给出一个二维数组,按照螺旋的方式输出;
  • 用四个指针控制每次上、下、左、右的边,然后按照逆时针的顺序从边界上依次访问元素;
  • 当访问完当前边界之后,要更新一下边界位置,缩小范围,方便下一轮进行访问;
  • 注意由于输入的数组 matrixm * n 的矩阵,m 不一定等于 n,所以在螺旋遍历时可能出现多遍历了行或者列,返回时需要删除 res 中多余的数: res.slice(0, m * n)

代码

/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function (matrix) {
	let m = matrix.length;
	let n = matrix[0].length;
	let res = [];
	let count = 0;
	let left = 0;
	let right = n - 1;
	let top = 0;
	let bottom = m - 1;

	while (count < m * n) {
		for (let i = left; i <= right; i++) {
			res[count] = matrix[top][i];
			count++;
		}
		top++;
		for (let i = top; i <= bottom; i++) {
			res[count] = matrix[i][right];
			count++;
		}
		right--;
		for (let i = right; i >= left; i--) {
			res[count] = matrix[bottom][i];
			count++;
		}
		bottom--;
		for (let i = bottom; i >= top; i--) {
			res[count] = matrix[i][left];
			count++;
		}
		left++;
	}
	return res.slice(0, m * n);
};

相关题目

题号标题题解标签难度力扣
59螺旋矩阵 II[✓]数组 矩阵 模拟🟠🀄️open in new window 🔗open in new window
885螺旋矩阵 III数组 矩阵 模拟🟠🀄️open in new window 🔗open in new window
2326螺旋矩阵 IV数组 链表 矩阵 1+🟠🀄️open in new window 🔗open in new window