类似这种:
- 1 2 3 4 5
- 12 13 14 6
- 11 15 7
- 10 8
- 9
认为第二种方法简单还是第一种方法简单直接决定了你的水平.
package test;
/**
* 二维数组 三角填充
* 1 2 3 4 5
* 12 13 14 6
* 11 15 7
* 10 8
* 9
*
* 1 2 3 4 5 6
* 15 16 17 18 7
* 14 21 19 8
* 13 20 9
* 12 10
* 11
*
* 1 2 3 4 5 6 7
* 18 19 20 21 22 8
* 17 27 28 23 9
* 16 26 24 10
* 15 25 11
* 14 12
* 13
* @author fans
*/
public class ArrayTest {
public static void main(String[] args) throws InterruptedException {
ArrayTest a = new ArrayTest();
int count = 12;//第一排数字的个数
//从小到大排序
long begin = System.currentTimeMillis();
int[][] bc = a.TriangleFill(count);
long end = System.currentTimeMillis();
System.out.println(end - begin);
//从大到小排序
//begin = System.currentTimeMillis();
//int[][] bc1 = a.rTriangleFill(count);
//end = System.currentTimeMillis();
//System.out.println(end - begin);
//输出结果
for(int i = 0; i < count; i++)
{
int size = bc[i].length;
for(int j = 0; j < size; j++)
{
int number = bc[i][j];
if(number > 0)
{
System.out.print(number + "\t");
}
}
System.out.println("\n");
}
}
//第一种:从最小一个数依次添加(正推)
public int[][] TriangleFill(int count)
{
//创建对应数量及大小的数组
int[][] arr = new int[count][];
int size = count;
for(int i = 0; i < count; ++i)
{
arr[i] = new int[size];
size--;
}
int n = count; //方向的次数
int direction = 0;// 方向 0 右 1 下 2上
int x = 0, y = -1;每个点的坐标
int num = 1;//数值
while(n > 0)
{
for(int i = 0; i < n; ++i)
{
switch(direction) {
case 0:
arr[x][++y] = num++;
if(i + 1 >= n)direction = 1;//改变方向
break;
case 1:
arr[++x][--y] = num++;
if(i + 1 >= n)direction = 2;//改变方向
break;
case 2:
arr[--x][y] = num++;
if(i + 1 >= n)direction = 0;//改变方向
break;
}
}
n--;
}
return arr;
}
//第二种:从最大一个点依次往外添加(逆推, 个人倾向于这种方法,逆天而行才是王道!-.-)
public int[][] rTriangleFill(int count)
{
//创建对应数量及大小的数组
int[][] arr = new int[count][];
int size = count;
for(int i = 0; i < count; ++i)
{
arr[i] = new int[size];
size--;
}
int max = (count + 1) * count / 2; //最大值 等差数列公式:(1+n)n/2
int direction = count % 3 ; // 最大值的方向0 下 1 左 2上
int x = count >=2 ? (count - 1) / 3 : 0;//最大值的x
int y = count >=2 ?(count + 1) / 3 : 0; //最大值的y
int beginPoint = 1;
while(max > 0)
{
for(int i = 0; i < beginPoint; ++i)
{
switch(direction) {
case 0:
if(i + 1 >= beginPoint)direction = 2;
arr[y++][x] = max--;
break;
case 1:
if(i + 1 >= beginPoint)direction = 0;
arr[y][x--] = max--;
break;
case 2:
if(i + 1 >= beginPoint)direction = 1;
arr[y--][x++] = max--;
break;
}
}
beginPoint++;
}
return arr;
}
}