矩形的逆时针蛇形填数

矩形的逆时针蛇形填数

主程序代码: 
import java.util.*;   
public class Snake { 
  static int a[][]=new int [15][15];  
   public static void main(String[] args) { 
         Scanner input=new Scanner(System.in);  
         int N=input.nextInt(); 

         //定义四个方向,分别为 右、下、左、上 
         int[][] direction={{0,1},{1,0},{0,-1},{-1,0}};          
         int[][] matrix=new int[N][N];        

         //x,y分别代表了矩阵中的行和列        
         int x=0,y=N-1; 
         int d=1;  
         for(int i=0; i<N*N; i++) {  
          //正常情况一直累加            
          matrix[x][y]=i+1;  
          x+=direction[d][0];               
          y+=direction[d][1]; 
         // x>=0 x<N y>=0 y<N 用于保证矩阵的元素必须在矩阵内  
         //,matrix用于保证 设置过矩阵位置的元素不被覆盖掉 
          if(!(x>=0 && x<N && y>=0 && y<N) || matrix[x][y]!=0) {  
             //如果以上情况不满足,证明x 和 y 的值需要撤销掉,       
             x-=direction[d][0];  
             y-=direction[d][1];                   
             ++d;  
            //四个方向 0 1 2 3                  
            d%=4;  
            //重新调整后的方向                  
            x+=direction[d][0];                   
           }           
       }  
      for(int[] o:matrix) {  
         for(int i:o)  
            System.out.print(i+" ");                
      System.out.println();         
     } 
  }
原文地址:https://www.cnblogs.com/lllini/p/11955307.html