编程思想练习题

论坛 期权论坛 脚本     
匿名技术用户   2021-1-2 09:36   11   0
package com.itheima;

import java.util.Scanner;
/**
 * Method_1利用螺旋填充法
 * @author Liang ZhiWu
 * @version 1.0
 */
public class MyDemo
{
 public static void main(String[] args)
 {
  
  Method_1.method();
 }  
}


class Method_1
{
 /**
  * 算法:螺旋填充法
  * 将m*m方阵分成一层一层的回形, 每个回形从角标相等的元素位置
  * 开始沿着顺时针方向遍历每一个位置
  * 遍历完外层再到往里的一层(m-2)*(m-2),一直遍历到最中心位置
  * 每一层的四条边分别用四个for循环遍历填充
  * 
  * 
  */
 public static void method()
 { 
  
  Scanner in=new Scanner(System.in);
  int x = in.nextInt(); //参数由用户输入
   
  while(x<=0)
  {
   System.out.println("请输入一个正整数");
   x = in.nextInt();
  }
  int col = 2*x-1;//根据输入参数计算方阵大小
  int row = 2*x-1;
  int[][] arr = new int[row][col];//创建空方阵
  
  int a = 1;//要填充的数
  for(int i=0;i<x;i++,a++)//回形层
  {
   int r = row - 1 - i;
   int c = col - 1 - i;
   for(int j=i;j<c;j++) arr[i][j]=a;//回形的上边自左而右进行填充
   for(int j=i;j<r;j++) arr[j][c]=a;//回形的右边自上而下进行填充
   for(int j=c;j>i;j--) arr[r][j]=a;//回形的下边自右而左进行填充
   for(int j=r;j>i;j--) arr[j][i]=a;//回形的左边自下而上进行填充
  }
  
  //中心的需要另外填充
  arr[x-1][x-1] = x;
   
   // 打印输出
  for(int i=0;i<x*2-1;i++)
  {
   for(int j=0;j<x*2-1;j++)
   {
    System.out.printf("%3d",arr[i][j]);
   }
  System.out.println();
  }
 }
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP