import java.util.*; public class CycleSquare{ public static void main(String[] args) { int[][] result=getSquare(5); printSquare(result); } public static int[][]getSquare(int x){ int[][] direction={{0 , 1}, //offset of row and column when direction is east. {1 , 0}, //south {0 ,-1}, //west {-1, 0} //north }; int[][] result=new int[x][x]; int row=0,column=0; int num=1; int d=0; //east int nextRow=0,nextColumn=0;
http://topic.csdn.net/u/20080114/22/48153ab5-a7ea-4246-972b-5e4c9f868430.html
public class CycleSquare{
public static void main(String[] args) {
int[][] result=getSquare(5);
printSquare(result);
}
public static int[][]getSquare(int x){
int[][] direction={{0 , 1}, //offset of row and column when direction is east.
{1 , 0}, //south
{0 ,-1}, //west
{-1, 0} //north
};
int[][] result=new int[x][x];
int row=0,column=0;
int num=1;
int d=0; //east
int nextRow=0,nextColumn=0;
while(num<=x*x){
result[row][column]=num++;
nextRow=row+direction[d][0];
nextColumn=column+direction[d][1];
if(nextRow==x||nextColumn==x||nextRow<0||nextColumn<0||result[nextRow][nextColumn]!=0){
d=(d+1)%4;
}
row+=direction[d][0];
column+=direction[d][1];
}
return result;
}
public static void printSquare(int[][] arr){
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr[i].length;j++){
System.out.printf("%5d",arr[i][j]);
}
System.out.println();
}
}}F:\java>java CycleSquare
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9