从中心开始,逆时针打印 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,15func 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)总结
以上是内存溢出为你收集整理的用Swift3实现从中心开始,逆时针打印 n*n 矩阵全部内容,希望文章能够帮你解决用Swift3实现从中心开始,逆时针打印 n*n 矩阵所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)