题目:给定一个N*N的二维数组,将二维数组旋转90度.
核心代码:
func rotate(data:inout [[Int]],n:Int) {
for layer in 0..<n / 2 {
let first:Int = layer
let last:Int = n - 1 - first
for i in first..<last {
let offset:Int = i - first
let top:Int = data[first][i] // top 数值
data[first][i] = data[last - offset][first] // 从左到上
data[last - offset][first] = data[last][last - offset] // 从下到左
data[last][last - offset] = data[i][last] // 从右到下
data[i][last] = top // 从上到右
}
}
}
测试代码:
var rotateData:[[Int]] = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
myString.rotate(data: &rotateData, n: 4)
print("FlyElephant--数组旋转90度数据---\(rotateData)")