方欣科技算法面试:蛇形矩阵2

来源:互联网 发布:淘宝直通车开车后流程 编辑:程序博客网 时间:2024/05/22 06:24

1 题目描述

/**
 * 蛇形矩阵2
 * 
 * 输入4
 * 
 * 输出
 *  1 12 11 10
 *  2 13 16 9
 *  3 14 15 8
 *  4 5 6 7
 * 
 * 
 * */

2  java代码


package 公司面试.方欣科技;/** * 蛇形矩阵2 *  * 输入4 *  *输出 *  1121110 *  213169 *  314158 *  4567 *  *  * */public class SnakeMatrix2 {      public void snakeMatrix2(int n){   if(n < 1){   System.out.println("请输入一个大于0的整数");   return ;    }   int row=-1; // 矩阵横坐标   int col=0; // 矩阵纵坐标   int counter = 0; //计数器   int[][] array = new int[n][n];//初始化矩阵   int direction = 0; // direction 为方向 (0 向下 , 1 向右, 2 向上 , 3 向左)   while( counter < n*n){   counter++;   //向下   if( direction==0 && row+1 < n && array[row+1][col] ==0 ){   row++;   if(row==n-1 || array[row+1][col] !=0){   direction = 1;     }   }   //向右   else if(direction==1 && col+1 < n && array[row][col+1] ==0 ){   col++;   if(col==n-1 || array[row][col+1] !=0){   direction = 2;     }   }   //向上   else if(direction==2 && row-1 >= 0 && array[row-1][col] ==0 ){   row--;   if(row==0 || array[row-1][col] !=0){   direction = 3;     }   }   //向左   else if(direction==3 && col-1 >= 0 && array[row][col-1] ==0 ){   col--;   if(col==0 || array[row][col-1] !=0){   direction = 0;     }   }     array[row][col] = counter;   }     this.show(array);   }   private void show(int v[][]){   if(v==null||v.length==0) return ;   for(int i = 0 ; i < v.length ; i++){   if(i!=0) System.out.println();   for(int j = 0 ; j < v.length ; j++){   System.out.print(v[i][j]+"");   }   }   }   public static void main(String args[]){   SnakeMatrix2 snakeMatrix = new SnakeMatrix2();   snakeMatrix.snakeMatrix2(5);   }}


3 输出结果



0 0
原创粉丝点击