zoukankan      html  css  js  c++  java
  • 用二维数组输出螺旋方阵(JAVA实现)

    思路一:

    public class Main {
        public static void main(String[] args) throws IOException{
            int[][] a = print(8);
            for(int[] el : a) {
                for(int e : el) {
                    System.out.printf("%4d", e);
                }
                System.out.println("");
            }
        } 
        
        public static int[][] print(int n) {
            int[][] array = new int[n][n];
            int count = 0; //层数
            int f = 0;
            while(count<n/2) {
                for(int i=0; i<n-2*count-1; i++) {
                    array[count][count+i] = 1+i+f; //上侧-从左到右
                    array[count+i][n-count-1] = (1+i+f)+(n-2*count-1); //右侧-从上到下
                    array[n-count-1][n-1-count-i] = (1+i+f)+2*(n-2*count-1); //下侧-从右到左
                    array[n-1-count-i][count] = (1+i+f)+3*(n-2*count-1); //左侧-从下到上
                }
                count++;
                f += 4*(n-2*count+1);
            }
            if(n%2==1) {
                array[n/2][n/2] = (int) Math.pow(n, 2);
            }
            return array;
        }
        
    }

    思路二:

    public static int[][] printMatrix(int n) {
            int[][] res = new int[n][n];
            int left=0;
            int top=0;
            int right=n-1;
            int bottom=n-1;
            int count = 1;
            while(left<=right&&top<=bottom) {
                for(int j=left; j<=right; j++) {
                    res[top][j]=count++;
                }
                for(int i=top+1; i<=bottom; i++) {
                    res[i][right]=count++;
                }
                if(top!=bottom) {
                    for(int j=right-1; j>=left; j--) {
                        res[bottom][j]=count++;
                    }
                }
                if(left!=right) {
                    for(int i=bottom-1; i>top; i--) {
                        res[i][left]=count++;
                    }
                }
                
                left++;
                top++;
                right--;
                bottom--;
            }
            return res;
        }

    output:

       1   2   3   4   5   6   7   8

      28  29  30  31  32  33  34   9

      27  48  49  50  51  52  35  10

      26  47  60  61  62  53  36  11

      25  46  59  64  63  54  37  12

      24  45  58  57  56  55  38  13

      23  44  43  42  41  40  39  14

      22  21  20  19  18  17  16  15

    转载请注明出处

  • 相关阅读:
    ScottGu: 宣布微软 AJAX CDN
    表格数据流协议TDS
    .NET 4 System.Threading.Barrier 类
    企业架构思考
    OpenSSL的托管项目
    WCF服务中操作FormsAuthentication的Cookie
    Silverlight相关博客收集20090927
    Sync Framework 2.0
    [中央电视台·见证]大学堂——兰州大学
    系统进程管理工具Process Explorer
  • 原文地址:https://www.cnblogs.com/macyzhang/p/9877592.html
Copyright © 2011-2022 走看看