【发布时间】:2019-03-16 18:54:05
【问题描述】:
给定一个 m x n 维的二维数组,我如何以逆时针方式循环遍历它们?
例如:
matrix = [
[ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ],
[ 9, 10, 11, 12 ],
[ 13, 14, 15, 16 ]
]
1st loop: 1, 5, 9, 13, 14, 15, 16, 12, 8, 4, 3, 2
2nd loop: 6, 10, 11, 7, 6
我真的不介意实现是用 ruby 还是 js 给出的
我目前的解决方案是这样的:
(1..rotate).each do
bottom_left_corner = i
top_right_corner = j
start_nth_layer = 1; end_nth_layer = matrix.length - 2
matrix.reverse_each do
matrix[bottom_left_corner].unshift(matrix[bottom_left_corner - 1].shift) if bottom_left_corner > 0
matrix[top_right_corner] << matrix[top_right_corner + 1].pop if top_right_corner < matrix.length - 1
bottom_left_corner -= 1; top_right_corner += 1
end
nth_layer(matrix, start_nth_layer, end_nth_layer)
end
更新
输出不格式化没关系,只要输出顺序正确。
问题的目的
这个问题的目的是逆时针遍历这些数组,一层一层,直到没有更多的层。对于每次遍历,我们逆时针移动值。例如:
Iteration 1: Iteration 2: Iteration 3:
============== ============= ==============
1 2 3 4 2 3 4 8 3 4 8 12
5 6 7 8 1 7 11 12 2 11 10 16
9 10 11 12 => 5 6 10 16 => 1 7 6 15
13 14 15 16 9 13 14 15 5 9 13 14
【问题讨论】:
-
你有没有尝试过?
-
这就像一个面试问题。
-
@TonyDong 我在hackerrank中尝试这个有趣的算法问题
-
@choz 否,因此 (M x N)。其中 N 和 M 可以是任意维度
-
您的“第二个循环”应以
7结尾。注意6已经被遍历过了。
标签: javascript arrays ruby loops multidimensional-array