62,614
社区成员
发帖
与我相关
我的任务
分享
public static void main(String args[]){
setValue(20,20);
}
public static void setValue(int width,int height){
int nums[][] = new int[width][height];
int direction = 0;// 0:右 1:下 2:左 3:上
int ind_x = 0;
int ind_y = 0;
for (int i = 0; i < width * height; i++) {
nums[ind_x][ind_y] = i + 1;
int []p = getFuturePos(direction,ind_x,ind_y);
if(p[0] < 0 || p[0] >= width || p[1] < 0 || p[1] >= height || nums[p[0]][p[1]] != 0){
++ direction;
p = getFuturePos(direction,ind_x,ind_y);
}
ind_x = p[0];
ind_y = p[1];
}
for (int i = 0; i < nums[0].length; i++) {
for (int j = 0; j < nums[1].length; j++) {
System.out.print(nums[i][j] + "\t");
}
System.out.println();
}
}
public static int[] getFuturePos(int direction ,int x ,int y){
int []p = new int[2];
p[0] = x;
p[1] = y;
switch(direction % 4){
case 2: //左
--p[1] ;
break;
case 3://上
--p[0];
break;
case 1: //下
++p[0];
break;
case 0: //右
++p[1];
break;
}
return p;
}
/*
1 2 3 4 5 6 7 8 9 10
36 37 38 39 40 41 42 43 44 11
35 64 65 66 67 68 69 70 45 12
34 63 84 85 86 87 88 71 46 13
33 62 83 96 97 98 89 72 47 14
32 61 82 95 100 99 90 73 48 15
31 60 81 94 93 92 91 74 49 16
30 59 80 79 78 77 76 75 50 17
29 58 57 56 55 54 53 52 51 18
28 27 26 25 24 23 22 21 20 19
*/
public static void main(String[] args) {
final int count = 10;
final int max = count * count;
final int[][] data = new int[count][count];
int x = -1, y = 0, cur = 0;
while (cur < max) {
for (; x + 1 < count && data[x + 1][y] == 0; data[y][++x] = ++cur);
for (; y + 1 < count && data[x][y + 1] == 0; data[++y][x] = ++cur);
for (; x > 0 && data[y][x - 1] == 0; data[y][--x] = ++cur);
for (; y > 0 && data[y - 1][x] == 0; data[--y][x] = ++cur);
}
for (int i = 0; i < count; ++i) {
for (int j = 0; j < data[i].length; ++j) {
System.out.printf("%-3d ", data[i][j]);
}
System.out.println();
}
}