Java 螺旋陣列的實現方式-一個迴圈實現哦
阿新 • • 發佈:2019-02-17
隨著程式設計的學習和工作,感觸越來越深的,就是如何做好對需求的理解。那麼在學習的過程中,就是如何將一個實際問題,轉化成計算機語言去實現。我覺得我的這方面的能力很是欠缺啊。
今天分享一下一個螺旋陣列例子的分析:
貼上code:
package excesize; /* * 螺旋陣列: * 4 * 1 2 3 4 * 12 13 14 5 * 11 16 15 6 * 10 9 8 7 */ public class LuoxuanArray { public static void main(String[] args){ int len=4; int[][] arr=luoxuanStart(len); for(int i=0;i<len;i++){ for(int j=0;j<len;j++) { System.out.print(+arr[i][j]+"\t"); } System.out.println(); } } public static int[][] luoxuanStart(int len){ /* * 定義一個整形方向變數,預設值為:0 * 0:向右;1:向下;2:向左;3:向上 */ final int toRight=0;//為什麼要定義成final型別 final int toDown=1; final int toLeft=2; final int toUp=3; int currentDirection=toRight; //定義一個二維陣列,用於存放二維的螺旋陣列值 int x=0,y=0;//定義二維陣列的下標 int[][] luoxuan=new int[len][len]; for(int i=1;i<=len*len;i++){//----------------------------------for //給當前座標賦值 luoxuan[x][y]=i; //計算下一個正確座標-這個座標不一定正確,所以先將此座標的位置 int tempX = x; int tempY = y; //根據當前的方向確定下一個位置的座標--------switch switch (currentDirection){ case toRight:{ tempY++; break; } case toDown:{ tempX++; break; } case toLeft:{ tempY--; break; } case toUp:{ tempX--; break; } }//-----------------------------switch //2.2、下一個座標如果正確,就賦值。否則,就轉向,並賦值。 /* * 座標值在正確的範圍,並且該座標未被賦過值,才是正確的座標值 */ if(tempX>=0 && tempX<len && tempY>=0 && tempY<len && luoxuan[tempX][tempY]==0){ //如果是正確的座標,將臨時座標賦給實際座標 x=tempX; y=tempY; }else{ //開始轉向 下一個方向 = (curDir+1)%4 currentDirection=(currentDirection+1)%4;//四個方向 switch (currentDirection){ case toRight:{ y++; break; } case toDown:{ x++; break; } case toLeft:{ y--; break; } case toUp:{ x--; break; } }//-------------------switch }//-----------------------------------if }//------------------------------------------------------for return luoxuan; }//-----------------------------------------------------------------------luoxuanStart }