用Swift3实现n*n阶矩阵顺时针输出

//: Playground - noun: a place where people can play

//import UIKit
/*
 顺时针打印N*N矩阵
 */


func anticlockwiseNN(n:Int){
    var m=1;
    var a = [[Int]]();
    for _ in 0..<n {
        //初始化矩阵元素为0
        var b = [Int]()
        for _ in 0..<n {
            b.append(0)
            
        }
        
        a.append(b)
        
    }
    for i in 0 ..< n/2 {  //只旋转n/2次
        
        for j in i ..< (n-i) { //向右
            if a[i][j] == 0 {
                a[i][j] = m
                m = m + 1
            }
        }
        
        for j in (i+1) ..< (n-i) { //向下
            if(a[j][n-i-1] == 0){
                a[j][n-i-1] = m ;
                m = m + 1 ;
            }
        }
        
        for j in ( i ..< (n-i)).reversed(){ //向左
            if a[n-i-1][j] == 0 {
                a[n-i-1][j] = m ;
                m = m + 1
            }
        }
        
        for j in  (i ..< (n-i-1)).reversed()  { //向上
            if a[j][i] == 0 {
                a[j][i] = m
                m = m + 1
            }
        }
        
        
        
        
        
    }
    
    
    if(n%2==1){//注意!当n为奇数时,有个正中心点
        a[n/2][n/2] = m;
    }
    
    
    for i in 0..<n {
        //初始化矩阵元素为0
        var s = "";
        for j in 0..<n {
            if a[i][j] < 10 {
                s = s + "0"
            }
            s = s + String(a[i][j]) + " "
        }
        print(s)
    }
}


anticlockwiseNN(n: 6)

相关文章

Swift 正式开源!Swift 团队很高兴宣布 Swift 开始开源新篇章。自从苹果发布 Swfit 编程语言,就成为了...
快,快,快!动动您的小手,分享给更多朋友! 苹果去年推出了全新的编程语言Swift,试图让iOS开发更简单...
开发者(KaiFaX) 面向开发者、程序员的专业平台! 和今年年初承诺的一样,苹果贴出了Swift语言的源码,...
本文由@Chun发表于Chun Tips :http://chun.tips/blog/2014/12/11/shi-yong-swift-gou-jian-zi-ding-yi...
本文由CocoaChina译者leon(社区ID)翻译 原文:THE RIGHT WAY TO WRITE A SINGLETON 在之前的帖子里聊过...
本文由CocoaChina译者leon(社区ID)翻译 原文:THE RIGHT WAY TO WRITE A SINGLETON 在之前的帖子里聊过...