circlearray.java

来自「关于数组的一些算法」· Java 代码 · 共 52 行

JAVA
52
字号
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 + =
减小字号Ctrl + -
显示快捷键?