• careercup题目20131010


    Spiraly print n*n matrix. 
    Eg: [1,2,3,4] 
    [12,13,14,5] 
    [11,16,15,6] 
    [10,9,8,7] 

    Should print 
    1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16

    螺旋输出n*n矩阵

    分析:n*n矩阵可分为n-2层输出,每层按照顺时针方向输出,每层输出的开始元素下标为 A[i][i]

    public class PrintMatrix {
    
        /**
         * question:
         * Spiraly print n*n matrix. 
            Eg: [1,2,3,4] 
            [12,13,14,5] 
            [11,16,15,6] 
            [10,9,8,7] 
            
            Should print 
            1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
         */
        public static void main(String[] args) {
            int[][] A = { { 1,  2,  3,  4 }, 
                      { 12, 13, 14, 5 }, 
                      { 11, 16, 15, 6 },
                      { 10,  9,  8, 7 } };
            int[][] B ={{ 0,  1,  2,  3, 4},
              {15, 16, 17, 18, 5},
              {14, 23, 24, 19, 6},
              {13, 22, 21, 20, 7},
              {12, 11, 10, 9, 8}};
            System.out.println(printMatrix(A));
            System.out.println(printMatrix(B));
        }
        
        public static String printMatrix(int[][] A){
            StringBuffer sb = new StringBuffer();
            int n = A.length;
            for(int i=0;i<n-2;i++){
                for(int j=i;j<n-i-1;j++){
                    sb.append(String.valueOf(A[i][j])).append(" ");
                }
                for(int j=i;j<n-i-1;j++){
                    sb.append(String.valueOf(A[j][n-i-1])).append(" ");
                }
                for(int j=n-i-1;j>i;j--){
                    sb.append(String.valueOf(A[n-i-1][j])).append(" ");
                }
                for(int j=n-i-1;j>i;j--){
                    sb.append(String.valueOf(A[j][i])).append(" ");
                }
            }
            return sb.toString();
        }
    
    }
  • 相关阅读:
    python函数练习题2
    python函数练习题1
    数字是否是10的整数倍
    关于循环的作业:登陆程序
    用for循环写这段代码
    while循环语句
    在CentOS8 上安装Python3
    时隔半年再写购物车程序并改进
    vue上传
    根据生日计算年龄
  • 原文地址:https://www.cnblogs.com/caijing/p/3362467.html
Copyright © 2020-2023  润新知