# 54 螺旋矩阵

# 题目链接

# 难度:中等

# 思路分析:

环形遍历、

#

#

#

#

#

#

#

#

#

#

#

#

#

#

# 代码:

环形遍历 设置四个边界 由外向内遍历

var spiralOrder = function(matrix) {
	if (matrix.length === 0) return []
	const res = []
	let top = 0,
		bottom = matrix.length - 1,
		left = 0,
		right = matrix[0].length - 1
	while (top < bottom && left < right) {
		for (let i = left; i < right; i++) res.push(matrix[top][i]) // 上层
		for (let i = top; i < bottom; i++) res.push(matrix[i][right]) // 右层
		for (let i = right; i > left; i--) res.push(matrix[bottom][i]) // 下层
		for (let i = bottom; i > top; i--) res.push(matrix[i][left]) // 左层
		right--
		top++
		bottom--
		left++ // 四个边界同时收缩,进入内层
	}
	// 剩下一行,从左到右依次添加
	if (top === bottom && left <= right)
		for (let i = left; i <= right; i++) res.push(matrix[top][i])
	// 剩下一列,从上到下依次添加
	else if (left === right && top <= bottom)
		for (let i = top; i <= bottom; i++) res.push(matrix[i][left])
	return res
}
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

环形遍历到底 中途退出

var spiralOrder = function(matrix) {
	if (matrix.length == 0) return []
	const res = []
	let top = 0,
		bottom = matrix.length - 1,
		left = 0,
		right = matrix[0].length - 1
	// 即使top === bottom 或者 left === right 可能还剩一行或者一列
	while (top <= bottom && left <= right) {
		for (let i = left; i <= right; i++) res.push(matrix[top][i])
		top++ // i = top 如果是最后一项 那么下面一个for循环不会运行
		for (let i = top; i <= bottom; i++) res.push(matrix[i][right])
		right--
		// 跟上个方法的区别
		// 当top > bottom 或者 left > right 其中有条边界将交错
		// 即所有项都添加完成
		if (top > bottom || left > right) break
		for (let i = right; i >= left; i--) res.push(matrix[bottom][i])
		bottom--
		for (let i = bottom; i >= top; i--) res.push(matrix[i][left])
		left++
	}
	return res
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 鼓励我一下:

觉得还不错的话,给我的项目点个star

# 点个Star支持我一下~