原题见:[url]http://www.iteye.com/topic/545378[/url]
真的不知道叫什么名字好,就自己给起个“海螺式”初始化二维数据。
说的是深圳一家公司的面试题,要求打印如下结果:
看完题目,就没敢继续看下面的讨论,怕是别人给出答案,就自己想了想,写了起来。写完了,发现有的人的回答跟我的思路一致。不过用了不短的时间,若是真的笔试时,自己很难在规定的时间内完成(跑起来)。
思路就是根据数字的递增来初始化,使用四个标记right->down->left->up->right...循环下去。
测试结果:
snake.init(2);时也输出了预期的结果。
真的不知道叫什么名字好,就自己给起个“海螺式”初始化二维数据。
说的是深圳一家公司的面试题,要求打印如下结果:
int i=5;
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
int i=6
1 2 3 4 5 6
20 21 22 23 24 7
19 32 33 34 25 8
18 31 36 35 26 9
17 30 29 28 27 10
16 15 14 13 12 11
看完题目,就没敢继续看下面的讨论,怕是别人给出答案,就自己想了想,写了起来。写完了,发现有的人的回答跟我的思路一致。不过用了不短的时间,若是真的笔试时,自己很难在规定的时间内完成(跑起来)。
思路就是根据数字的递增来初始化,使用四个标记right->down->left->up->right...循环下去。
/**
* http://www.iteye.com/topic/545378?page=1
*/
public class PrintSnakeNumber {
private int len;
private int[][] snake;
/**
* @param len > 1
*/
public void init(int len){
if(len<2)
this.len=2;
this.len=len;
snake=calculate(this.len);
}
public int getLen(){
return this.len;
}
private final int[][] calculate(int len){
int[][] snake=new int[len][len];
int total=len*len;
int i,j=0; //array'index
int x=-1; //backup array's index
int y=0; //backup array's index
int value=1; //1...len^2, increased by one
final String right="right"; //only i++
final String down="down"; //only j++
final String left="left"; //only i--
final String up="up"; //only j--
final String stop="stop";
Map<String,Integer> map=new HashMap<String,Integer>();
map.put("right", 0);
map.put("down", 1);
map.put("left", 2);
map.put("up", 3);
String pos=right; //first turn right
while(!pos.equals(stop)){
switch(map.get(pos)){
case 0: //right
i=x+1;
j=y;
for(;i<len;i++){
if(snake[i][j]==0){
x=i;
y=j;
snake[i][j]=value++;
}else{
if(value>total)
pos=stop;
else
pos=down;
break;
}
} //end for
case 1: //down
i=x;
j=y+1;
for(;j<len;j++){
if(snake[i][j]==0){
x=i;
y=j;
snake[i][j]=value++;
}else{
if(value>total)
pos=stop;
else
pos=left;
break;
}
} //end for
case 2: //left
i=x-1;
j=y;
for(;i>=0;i--){
if(snake[i][j]==0){
x=i;
y=j;
snake[i][j]=value++;
}else{
if(value>total)
pos=stop;
else
pos=up;
break;
}
}//end for
case 3: //up
i=x;
j=y-1;
for(;j>=0;j--){
if(snake[i][j]==0){
x=i;
y=j;
snake[i][j]=value++;
}else{
if(value>total)
pos=stop;
else
pos=right;
break;
}
}//end for
} //end switch
} //end while
return snake;
}
public void printArray(){
for(int i=0;i<this.len;i++){
for(int j=0;j<this.len;j++)
System.out.print(this.snake[j][i]+"\t");
System.out.println();
}
}
}
测试结果:
public static void main(String[] args) {
PrintSnakeNumber snake=new PrintSnakeNumber();
snake.init(10);
snake.printArray();
}
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
snake.init(2);时也输出了预期的结果。