Amazon Campus(2013-Sep-24)Question 1 / 2 (Amazon Campus(15): Clock wise walk)

32 篇文章 0 订阅
30 篇文章 0 订阅
Question 1 / 2 (Amazon Campus(15): Clock wise walk)

Suppose we got a integer named size from input. size meet the rule:

size%2 ==1.

We use this size to build a square blocks, and we start from the center of block to go through all the array in clock wise. Please print the footstep sequence by number, please note we use asterisk to divide two neighbor numbers.
For example, we get size =3 from standard input, we should print following graph to standard output
7*8*9
6*1*2
5*4*3

For example, we get size =5 from standard input,we should print following graph to standard output
21*22*23*24*25
20*7*8*9*10
19*6*1*2*11
18*5*4*3*12
17*16*15*14*13

顺时针蛇形矩阵:

	static String clockwise(int size) {
    	String res = "";
    	int n,i,j,d = 0;
    	n = size;
    	int [][]a =new int[size+2][size+2];
    	a [1][n+1] = n*n+1;
    	while(d<=(n-1)/2)
    	{
	    	for(i = n-d ; i >= 1+d ; i--)
	    		a[1+d][i] = a[1+d][i+1] - 1;
	    	for(i = 2+d ; i <= n-d ; i++)
	    		a[i][1+d] = a[i-1][1+d] - 1;
	    	for(i = 2+d; i <= n-d ; i++)
	    		a[n-d][i] = a[n-d][i-1] - 1;
	    	for(i = n-1-d; i >= 2+d ; i--)
	    		a[i][n-d] = a[i+1][n-d] - 1;
	    	d++;
    	}
    	for(i=1;i<=n;i++)
    	{
	    	for(j=1;j<=n;j++)
	    	{
	    		if(j!=n) res += a[i][j] + "*";
	    		else res += a[i][j] + "\n";
	    	}
    	}
    	return res;
    }

下面是逆时针的蛇形矩阵:

    static String clockwise(int size) {
    	String res = "";
    	int n,i,j,d = 0;
    	n = size;
    	int [][]a =new int[size+2][size+2];
    	a [n][n+1] = n*n+1;
    	while(d<=(n-1)/2)
    	{
	    	for(i = n-d ; i >= 1+d ; i--)
	    		a[n-d][i] = a[n-d][i+1] - 1;
	    	for(i = n-1-d ; i >= 1+d ; i--)
	    		a[i][1+d] = a[i+1][1+d] - 1;
	    	for(i = 2+d; i <= n-d ; i++)
	    		a[1+d][i] = a[1+d][i-1] - 1;
	    	for(i = 2+d; i < n-d ; i++)
	    		a[i][n-d] = a[i-1][n-d] - 1;
	    	d++;
    	}
    	for(i=1;i<=n;i++)
    	{
	    	for(j=1;j<=n;j++)
	    	{
	    		if(j!=n) res += a[i][j] + "*";
	    		else res += a[i][j] + "\n";
	    	}
    	}
    	return res;
    }



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值