📄 circlearray.java
字号:
public class CircleArray{
static int[][] direction = {
{0,1}, // right
{1,0}, // down
{0,-1}, // left
{-1,0} // up
};
public static void main(String args[]){
int n = 5;
int[][] a = new int[n][n];
int col, row;
col = row = 0;
a[row][col] = 1;
int direct = 0;
for (int i = 2; i<= n*n ;++i){
//Step 1 选定一个方向
if (!testNext(a, direct, row, col))
direct = (direct + 1) % 4;
//Step 2 根据选定的方向,填入数值
row = row + direction[direct][0];
col = col + direction[direct][1];
a[row][col] = i;
}
for (int i = 0; i<a.length; ++i){
for (int j = 0; j<a[i].length; ++j){
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
}
public static boolean testNext(int[][] a, int direct, int row, int col){
row = row + direction[direct][0];
col = col + direction[direct][1];
//row out of bound
if ( (row >= a.length) || (row <0)) return false;
//col out of bound
if ( (col >= a.length) || (col < 0) ) return false;
//already have a value
if (a[row][col] != 0 ) return false;
return true;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -