- /*1 2 3 4 5
- 14 15 16 17 6
- 13 20 19 18 7
- 12 11 10 9 8
- 打印如上矩阵*/
- public class MainApp {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Cube text = new Cube(5,5); //这里的参数分别表示要打印的行数和列数
- System.out.print(text);
- }
- }
- import java.util.Arrays;
- /*这是实现类,构造方法的参数为一个row和一个coloum,形成一个矩阵*/
- public class Cube {
- int[] cube; //用于存放数据
- int row; //行数
- int coloum; //列数
- public Cube(int row,int coloum){ //构造函数
- /*初始化*/
- this.cube = new int[row*coloum];
- Arrays.fill(this.cube,0);
- this.row = row;
- this.coloum = coloum;
- this.initialarry();
- }
- //形成队列
- private void initialarry() {
- int step = 1; //下一步要走的值
- int id =0; //id号
- int next; //存forward函数;
- for(int i=1;i<=cube.length;i++){
- cube[id] = i;
- next = this.forward(id+1);
- if(next!=0){ //如果不等于0
- step=next;
- }
- id+=step; //确定下一步要要往哪里走
- }
- }
- @Override
- public String toString() {
- String output=""; //输出
- for(int i = 0;i<this.cube.length;i++){
- /*这是为了打印好看*/
- output+=cube[i]<10?" "+String.valueOf(cube[i]):" "+String.valueOf(cube[i]);
- if((i+1)%this.coloum==0){
- output+="/n";
- }
- }
- return output;
- }
- private int forward(int id){ //用于判断一个格子附近的4个格子是否为空
- int count=0; //计数器
- boolean[] forward = new boolean[4]; //表示方向
- Arrays.fill(forward,false); //初始化
- /*判断上面的格子*/
- if((id-this.coloum)>0 //不是最上面一行
- &&cube[id-this.coloum-1]==0){ //还没有赋值
- count++;
- forward[0] = true; //0表示向上
- }
- /*判断左面的格子*/
- if((id-1)>0 //序列号正常
- &&((id-1)%this.coloum)!=0 //不是最左面一列
- &&cube[id-2]==0){
- count++;
- forward[1] = true; //1表示向左
- }
- /*判断右的格子*/
- if((id+1)<=this.cube.length //序列号正常
- &&(id%this.coloum)!=0 //不是最右面一列
- &&cube[id]==0){
- count++;
- forward[2] = true; //2表示向右
- }
- /*判断下面的格子*/
- if((id+this.coloum)<=this.cube.length //序列号正常
- &&cube[id+this.coloum-1]==0){
- count++;
- forward[3] = true; //1表示向左
- }
- /*决定返回值*/
- if(count!=1){ //根据观察,如果朋友不为一个的话,是不会转向的。
- return 0;
- /*如果为一时,那里那里为空,网哪里走*/
- }else if(forward[0]){ //上面为空,往上走
- return -this.coloum;
- }else if(forward[1]){ //左面为空,往左走
- return -1;
- }else if (forward[2]){ //右面为空,往右走
- return 1;
- }else if(forward[3]){ //下面为空,往下走
- return this.coloum;
- }
- return 0;
- }
- }