Given aNXN matrix, starting from the upper right corner of the matrix start printingvalues in a counter-clockwise fashion.
E.g.: Consider N = 4
Matrix= {a, b, c, d,
e, f, g, h,
i, j, k, l,
m, n, o, p}
Your function should output: dcbaeimnoplhgfjk
分成四段 然后index依次减一 一共执行n/2次
对于n为奇数 最后再加入一个中间值
def spiral(a) ans, n = [], a.length n/2.times do |k| (k...n-k-1).each {|i| ans << a[k][i]} (k...n-k-1).each {|i| ans << a[i][n-k-1]} (k...n-k-1).each {|i| ans << a[n-k-1][-i-1]} (k...n-k-1).each {|i| ans << a[-i-1][k]} end ans << a[n/2][n/2] if n%2 == 1 ans end
时间: 2024-12-28 08:33:49