求50道基础题作者: mars314 时间: 2015-10-11 22:24
public class Test
{
public static void main(String[] args)
{
int number = 4;
int[][] arys = printCircle(number);
for (int i = 0; i < number; i++)
{
for (int j = 0; j < number; j++)
{
System.out.print(arys[i][j] + "\t");
}
System.out.println();
}
}
private static int[][] printCircle(int number)
{
int[][] ary = new int[number][number];
int rightLen;
int downLen;
int leftLen;
int upLen;
int rightRow = 0;
int rightCol = 0;
int leftRow = number - 1;
int leftCol = number - 1;
int downRow = 1;
int downCol = number - 1;
int upRow = number - 2;
int upCol = 0;
int digit = 1;
while (number > 0)
{
rightLen = number;
downLen = number - 1;
leftLen = number - 1;
upLen = number - 2;
// Step 1: print to right
for (int i = 0, temp = rightCol; i < rightLen; i++)
{
ary[rightRow][temp++] = digit++;
}
// Step 2: print to down
for (int j = 0, temp = downRow; j < downLen; j++)
{
ary[temp++][downCol] = digit++;
}
// move left
for (int m = 0, temp = leftCol - 1; m < leftLen; m++)
{
ary[leftRow][temp--] = digit++;
}
// move up
for (int n = 0, temp = upRow; n < upLen; n++)
{
ary[temp--][upCol] = digit++;
}