现在的位置: 首页 > 综合 > 正文

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

2018年02月18日 ⁄ 综合 ⁄ 共 1382字 ⁄ 字号 评论关闭
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;
    }

抱歉!评论已关闭.