zoukankan      html  css  js  c++  java
  • Java语言实现螺旋方阵

    螺旋方阵

    输入行数,输出其的螺旋方阵,其中所有数间隔至少为两个空格。比如:

    请输入行数(整数)5
    1     2     3    4   5
    16  17  18  19   6
    15  24  25  20   7
    14  23  22  21   8
    13  12  11  10   9

    import java.util.Scanner;
    
    public class TestOne{
    	public static void main(String [] args) {
    		Scanner sc = new Scanner(System.in);
    		System.out.print("请输入行数(整数)");
    		int n = sc.nextInt();
    		int m = n+2;
    		int [][] arr = new int[m][m];   // 同步 book
    		
    		// 标记 1 可以落脚,0 不可以落脚
    		int [][] book = new int[m][m];  // 为了标记四周, 数组开大一点
    		for(int i = 0;i < m;i++) 
    			if(i == 0 || i == m-1) 
    				for(int j = 0;j < m;j++) {
    					book[i][j] = 1;
    					book[j][i] = 1;
    				}
    		
    		// 添加数字
    		int [][] direction = {{0, 1}, {-1, 0}, {0, -1}, {1, 0}};    // 方向(右,下,左,上)
    		int i = 1, j = 0, dir = 0, value = 0;       // dir是方向 0123对应右,下,左,上,从 arr[1][0] 起,先向右一步 value 是值
    		while(value < n*n) {
    			// 判断下一步能不能落脚(期初是右边)
    			if(book[i+direction[dir%4][0]][j+direction[dir%4][1]] == 0) { // 可以落脚
    				i += direction[dir%4][0];    
    				j += direction[dir%4][1];
    				arr[i][j] = ++value;
    				book[i][j] = 1;          // 走过了,不能再落脚了
    			} else   // 不能落脚,则顺时针换方向
    				dir++;
    		}
    		
    		//输出
    		Integer maxnumber = new Integer(arr[n/2+1][n/2+1]);
    		int length = maxnumber.toString().length() + 2;       // 保证所有数间隔至少为两个空格
    		for(i = 1;i < m-1;i++) {
    			for(j = 1;j < m-1;j++) 
    				System.out.printf("%"+length+"d", arr[i][j]);
    			System.out.println();
    		}
    		
    		sc.close();
    	}
    
    }
    /* Code Running Results:
     * 请输入行数(整数)11
     *   1    2    3    4    5    6    7    8    9   10   11
     *  40   41   42   43   44   45   46   47   48   49   12
     *  39   72   73   74   75   76   77   78   79   50   13
     *  38   71   96   97   98   99  100  101   80   51   14
     *  37   70   95  112  113  114  115  102   81   52   15
     *  36   69   94  111  120  121  116  103   82   53   16
     *  35   68   93  110  119  118  117  104   83   54   17
     *  34   67   92  109  108  107  106  105   84   55   18
     *  33   66   91   90   89   88   87   86   85   56   19
     *  32   65   64   63   62   61   60   59   58   57   20
     *  31   30   29   28   27   26   25   24   23   22   21
     */
    
    
    
    
    
    
    
  • 相关阅读:
    延时调用的php代码
    mysql 官网下载太慢了,来这里!!!
    解决react-native 运行报错:Entry, ":CFBundleIdentifier", Does Not Exist
    mongodb增删改查常用命令总结
    Linux 查看文件内容(8)
    Linux mv命令(7)
    Linux文件拷贝(6)
    Linux 创建与删除(5)
    Linux cd命令(4)
    ls 命令通配符(3)
  • 原文地址:https://www.cnblogs.com/jiaohuadehulike/p/14295016.html
Copyright © 2011-2022 走看看