cubegao

Swift.顺时针打印矩阵

2015-07-11

题目描述:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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

Tags: 算法

扫描二维码,分享此文章