前端之家收集整理的这篇文章主要介绍了
用Swift3实现从中心开始,逆时针打印 n*n 矩阵,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
从中心开始,逆时针打印 n*n 矩阵
例如:
[ 0,1,2,3]
[ 4,5,6,7]
[ 8,9,10,11]
[ 12,13,14,15]
输出:
6,11,7,3,4,8,12,15
func printNN( n:Int){
var row = 0 ;
var col = 0;
if(n%2==0){//偶数行时
row = n/2;
col = row + 1;
}else{//奇数行时
row = (n+1)/2
col = row
}
var k = n - col //与外围相差多少个数字
var s = "";//最终的字符串
if(k<0){ // n = re1 时
print("0")
return
}
while(k > -1){
for d in 0..<4{
switch(d){
case 0 ://向上
// int i = row-1
let m = row - 2 ;
if m >= 0 && m > k - 1 {
var j = k
if j < 0 {
j = 0 ;
}
for i in (j ... m).reversed(){
if(s == ""){
s = rowCol(row: i,col: col-1,n: n)
}else{
s = s + "," + rowCol(row: i,n: n)
}
}
row = k + 1 ;
col = col - 1 ;
print(s + "===\(d)" )
}
break;
case 1 ://向左
let m = col-1
if m >= 0 && m > k - 1 {
if n % 2 == 1 && m <= k {
break
}
for i in (k ... m).reversed(){
if(s == ""){
s = rowCol(row: row-1,col: i," + rowCol(row: row-1,n: n)
}
}
row = row + 1 ;
col = k + 1 ;
print(s + "===\(d)" )
}
break;
case 2 ://向下
let m = row - 1
let j = n-k
if m < j - 1 && m>=0{
for i in m ..< j {
if(s == ""){
s = rowCol(row: i,n: n)
}
}
row = n - k ;
col = col + 1 ;
print(s + "===\(d)" )
}
break;
case 3 ://向右
// int i =
let m = col - 1
var j = n - k
if k > 0 {
j = j + 1
}
if m <= j - 1 && m >= 0 {
for i in m ..< j {
if(s == ""){
s = rowCol(row: row-1,n: n)
}
}
// row = row - 1 ;
col = n - k + 1 ;
print(s + "===\(d)" )
}
break;
default:
break;
}
}
k -= 1;
}
print(s)
}
func rowCol(row:Int,col:Int,n:Int )->String{
return String(row * n + col)
}
printNN(n: 6)