输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
例如:如果输入如下矩阵:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
则依次打印出数字1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10。
func arrayFromMatrix(matrix: [Array<Int>]) -> Array<Int> {
if matrix.count == 0 {
return []
}else if matrix.count == 1 {
return matrix.first!
}else if matrix.count == 2 {
var numbers = matrix.first!
var second = matrix.last!
for _ in second {
numbers.append(second.removeLast())
}
return numbers
}else {
var next: [Array<Int>] = []
var middle: [Array<Int>] = []
var numbers = matrix
var result = numbers.removeFirst()
var last = numbers.removeLast()
for var item in numbers {
result.append(item.removeLast())
middle.insert(item, at: 0)
item.removeFirst()
next.append(item)
}
for _ in last {
result.append(last.removeLast())
}
for var item in middle {
result.append(item.removeFirst())
}
result.append(contentsOf: arrayFromMatrix(matrix: next))
return result
}
}