打印蛇形矩阵-题解

按照格式:"打印蛇形矩阵"

Sample Input
5

Sample Output:
21 22 23 24 25
20 7   8    9  10
19 6   1    2  11
18 5   4    3  12
1716 15 14 13


Sample Input
7

Sample Output:

43 44 45 46 47 48  49
42 21 22 23 24 25  26
41 20 7   8    9  10   27
40 19 6   1    2  11   28
39 18 5   4    3  12   29
38 17 16 15 14 13  30
37 36 35 34 33 32  31

解题思路: 

                   按照数字的递增顺序,依次填充数值, 声明变量 index,从1......n*n 进行自增变化, 声明变量 x, y 两个指针,进行坐标位置的变化 , 清晰的思路,完成!

 

源码(java):

 

public class Main
{
 public static void main(String[] args)
 {
        int n = 7;
        int arr[][] = new int[n][n];
        int x = n/2, y = n/2;
      arr[x][y] = 1;
     int index = 2;
       
  for (int i = 0; i < n/2; i++)
  {
   y++;
   for (int j = 0; j < (i+1)*2; j++) arr[x++][y] = index++;
   x--;y--;
   for (int j = 0; j < (i+1)*2; j++) arr[x][y--] = index++;
   y++;x--;
   for (int j = 0; j < (i+1)*2; j++) arr[x--][y] = index++;
   x++;y++;
   for (int j = 0; j < (i+1)*2; j++) arr[x][y++] = index++;
   y--;
  }
  for (int i = 0; i < n; i++)
  {
   for (int j = 0; j < n; j++)
   {
    System.out.printf("%-2d ", arr[i][j]);
   }
   System.out.println();
  }
      
 }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值