数组练习_回形矩阵

/* * 回形数 从键盘输入一个整数(1~20) ,则以该数字为矩阵的大小,把 1,2,3…n*n 的 数字按照顺时针螺旋的形式填入其中 */ /* * 一共重复上右下左四个循环的动作、这四个动作重复执行、 * 因此需要一个for循环里面四个for循环 * 第一个for循环执行n/2次 */

''''

import java.util.Scanner;

/*
 * 回形数
从键盘输入一个整数(1~20) ,则以该数字为矩阵的大小,把 1,2,3…n*n 的
数字按照顺时针螺旋的形式填入其中
 */
/*
 * 一共重复上右下左四个循环的动作、这四个动作重复执行、
 * 因此需要一个for循环里面四个for循环
 * 第一个for循环执行n/2次
 */
public class RectangleTest {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("please input the size of matrix:");
    int size = scanner.nextInt();
    int[][] rectangleMatrix = new int[size][size];
    int count = 1;
    scanner.close();
    System.out.println(" rectangleMatrix.length:" + rectangleMatrix.length);
    for (int i = 0; i < rectangleMatrix.length / 2; i++) {
      // 横
      for (int j = i; j < rectangleMatrix.length - i; j++) {
        rectangleMatrix[i][j] = count++;
        // count++;

      }
      // 右
      for (int j = i + 1; j < rectangleMatrix.length - i - 1; j++) {
        rectangleMatrix[j][rectangleMatrix.length - i-1] = count++;
        // count++;
      }
      // 下
      for (int j = rectangleMatrix.length - i - 1; j >= i; j--) {
        rectangleMatrix[rectangleMatrix.length - i - 1][j] = count++;

      }

      // 左
      for (int j = size - i - 2; j >= i + 1; j--) {
        rectangleMatrix[j][i] = count++;

      }

    }
    //如果是奇数行、则需要对中间数字单独赋值
    if(count==size*size)
      rectangleMatrix[size/2][size/2]=count;
    for (int i = 0; i < rectangleMatrix.length; i++) {
      for (int j = 0; j < rectangleMatrix.length; j++) {
        System.out.print(rectangleMatrix[i][j] + "\t");
      }
      System.out.println();

    }

  }

}

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值