2018-03-17

求解:顺时针输出二维数组

给定一个 n*n 的二维数组矩阵矩阵,以顺时针顺序输出

1
2
3
4
5
举个栗子:
[ 0, 1, 2,
3, 4, 5,
6, 7, 8 ]
输出: 0, 1, 2, 5, 8, 7, 6, 3, 4

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
fun main(args: Array<String>) {
val cursor = Cursor(-1, 0)
val rect = makeRect(3)
rect.print()

clockwise(rect, 0, cursor)
}

typealias Matrix = Array<IntArray>

data class Cursor(var x: Int, var y: Int) {
fun up() = apply { y -= 1 }
fun down() = apply { y += 1 }
fun left() = apply { x -= 1 }
fun right() = apply { x += 1 }
}

fun clockwise(rect: Matrix, level: Int, cursor: Cursor) {
val rectLength = rect[0].size
val currentLength = rectLength - 2 * level

for (i in 0 until currentLength) {
cursor.right()
print(rect[cursor])
}
for (i in 0 until currentLength - 1) {
cursor.down()
print(rect[cursor])
}
for (i in 0 until currentLength - 1) {
cursor.left()
print(rect[cursor])
}
for (i in 0 until currentLength - 2) {
cursor.up()
print(rect[cursor])
}

if (currentLength < 0) {
return
} else {
clockwise(rect, level + 1, cursor)
}
}

private fun makeRect(n: Int) = Array(n) { IntArray(n) }.apply {
for (i in 0 until n * n) {
this[i / n][i % n] = i
}
}

private fun Matrix.print() = forEach { println(it.joinToString(",")) }
private operator fun Matrix.get(cursor: Cursor) = this[cursor.y][cursor.x]