题解 | #蛇形矩阵#
蛇形矩阵
https://www.nowcoder.com/practice/649b210ef44446e3b1cd1be6fa4cab5e
import Foundation
while let line = readLine() {
let n = Int(line)!
var mat = [[Int]](repeating: [Int](repeating: -1, count: n), count: n)
var k = 1
//! 广度优先
var queue = [(Int,Int)]()
queue.append((0,0))
while !queue.isEmpty {
let count = queue.count
for _ in 0..<count {
let tupe = queue.removeFirst()
if (mat[tupe.0][tupe.1] != -1) {
continue
}
mat[tupe.0][tupe.1] = k
k+=1
//! 第一个元素是 row 第二个元素是 col
if tupe.0 + tupe.1 + 1 < n {
queue.append((tupe.0+1,tupe.1))
queue.append((tupe.0,tupe.1+1))
}
}
}
for i in 0..<n {
var tempArray = [String]()
for j in 0..<n {
if (mat[i][j] != -1) {
tempArray.append(String(mat[i][j]))
}
}
print(tempArray.joined(separator: " "))
}
}
需要注意 矩阵的先后顺序。
查看12道真题和解析