题目描述:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.
import Foundation
class For20Solution {
func printMatrixClockwisely(_ n: [[Int]]) {
guard n.count > 0 else {
return
}
let rows = n.count
let cols = n[0].count
var start = 0
//每次的起点左上角(start,start)
while cols > start * 2 && rows > start * 2 {
printMatrix(n, rows, cols, start)
start += 1
}
}
func printMatrix(_ n: [[Int]],_ row: Int,_ col: Int,_ start: Int) {
let endX = col - 1 - start
let endY = row - 1 - start
//打印从start->endX,最上一行
if start <= endX {
var index = start
while index <= endX {
print(n[start][index])
index += 1
}
}
//打印从start-> endY,最右一列
if start <= endY {
var index = start + 1
while index <= endY {
print(n[index][endX])
index += 1
}
}
//打印从endX-> start,最下一行
if endX >= start {
var index = endX - 1
while index >= start {
print(n[endY][index])
index -= 1
}
}
//打印从endY-> start,最左一列
if endY >= start {
var index = endY - 1
while index > start {
print(n[index][start])
index -= 1
}
}
}
}
算法思想:先得到矩阵的行和列数,然后依次旋转打印数据,一次旋转打印结束后,往对角分别前进和后退一个单位。
github地址:https://github.com/cubegao/LeetCode