备考蓝桥杯(13)顺时针螺旋填入矩阵 java实现

package pers.robert.lanqiaobeizhenti129;

import java.util.Scanner;

/**
 * 25.顺时针螺旋填入
从键盘输入一个整数(1~20)
则以该数字为矩阵的大小,把1,2,3…n*n 的数字按照顺时针螺旋的形式填入其中。例如:
输入数字2,则程序输出:
1 2
4 3
输入数字3,则程序输出:
1 2 3
8 9 4
7 6 5
输入数字4,则程序输出:
1  2   3   4
12  13  14  5
11  16  15  6
10   9  8   7

 * @author Robert
 *
 */
public class The025ClockwiseSpiralFillingDemo1 {
	public static void print(int[][] array) {
		for (int i = 0; i < array.length; i++) {
			for (int j = 0; j < array.length; j++) {
				System.out.printf("%4d",array[i][j]);
			}
			System.out.println();
		}
	}
	public static void main(String[] args) {
		Scanner scanner=new Scanner(System.in);
		int n=scanner.nextInt();
		int array[][]=new int[n][n];
		int startIndex=0,endIndex=n-1,count=1,e=0;
		while (e<=n/2) {
			for (int i = startIndex; i <= endIndex; i++) {//第一行未填数据
				array[e][i]=count++;
			}
			for (int i = startIndex+1; i <= endIndex; i++) {//最后一列未填数据
				array[i][n-1-e]=count++;
			}
			for (int i = endIndex-1; i>=startIndex; i--) {
				array[n-1-e][i]=count++;//最后一行未填数字
			}
			for (int i = endIndex-1; i>startIndex; i--) {//第一列未填数字
				array[i][e]=count++;
				
			}
			
			startIndex++;
			endIndex--;
			e++;
		}
		print(array);
	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值