import java.util.Scanner;
public class TestPrint
{
//输入一个整数coun
Scanner in = new Scanner(System.in);
int coun = in.nextInt();
//定义二维数组
int[][] squar = new int[coun][coun];
//打印一个矩形
/*
*****
*****
*****
*****
*/
void print()
{
for (int i = 0; i < coun; i++)
{
for (int j = 0; j < coun; j++)
{
System.out.print(squar[j] + "\t ");
}
System.out.println();
}
}
//调整位置
//从左往右,从上到下,从右到左,从下到上
void generate()
{
int dx = 1, dy = 1, x = 0, y = 0, _x, _y;
boolean goHorizon = true;
//输入的值循环的次数coun*coun
for (int i = 1; i <= (coun*coun); i++)
{
squar[y][x] = i;
if (goHorizon)
{
_x = x + dx;
if (_x > (coun-1) || _x < 0 || squar[y][_x] != 0)
{
goHorizon = false;
dx = -dx;
y += dy;
} else {
x = _x;
}
} else
{
_y = y + dy;
if (_y > (coun-1) || _y < 0 || squar[_y][x] != 0) {
goHorizon = true;
dy = -dy;
x += dx;
} else {
y = _y;
}
}
}
}
public static void main(String[] args)
{
TestPrint test = new TestPrint();
test.generate();
test.print();
}
}
打印出结果:
|