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

1 题目描述

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

2  java代码


package 公司面试.方欣科技;

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

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值