ITeye博客

内螺旋数组java实现

oboaix · 2014-09-15 23:14 · JAVA · 编程语言 · Markdown

最初学习C语言时,看到国外程序员的内螺旋实现,都懵了,感觉超级复杂,一直没有去检查具体是如何实现的,最近又再次看到这种,想通过java语言也来完成这个方式,具体代码如下:

/**
 * 
 * @author dennis zhao
 * General logical way of thinking
 * 2013-09-15
 */
public class InnerSprialArray {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		print();
		for (int i = 0; i < result.length; i++) {
			for (int j = 0; j < result[i].length; j++) {
				int a = result[i][j];
				if (a==1) {
					System.out.print((a < 10 ? "0" + a : a ) + "○" + "\t");
				} else if (a == COL * ROW){
					System.out.print((a < 10 ? "0" + a : a ) + "●" + "\t");
				} else {
					System.out.print((a < 10 ? "0" + a : a ) + directions[i][j] + "\t");
				}
			}
			System.out.println();
		}
	}

	/**
	 * simple logic: from left ---> right; top ---> down; right ---> left;  down ---> top;
	 * if find accessed element, it change direction
	 */
	private static void print() {
		int count = 0;
		int row = 0;
		int col = -1;
		while (count < COL * ROW) {
			// left to right
			col++;
			while (col < COL && initial[row][col] == 0) {
				initial[row][col] = 1;//if no access(0), it change this access flag = 1
				count++;
				result[row][col] = count;
				directions[row][col] = "→";
				col++;
			}
			col--;// last column minus 1

			// top to down
			row++;
			while (row < ROW && initial[row][col] == 0) {
				initial[row][col] = 1;
				count++;
				result[row][col] = count;
				directions[row][col] = "↓";
				row++;
			}
			row--;// last row minus 1

			// right to left
			col--;
			while (col >= 0 && initial[row][col] == 0) {
				initial[row][col] = 1;
				count++;
				result[row][col] = count;
				directions[row][col] = "←";
				col--;
			}
			col++;// last column add 1

			// down to top
			row--;
			while (row >= 0 && initial[row][col] == 0) {
				initial[row][col] = 1;
				count++;
				result[row][col] = count;
				directions[row][col] = "↑";
				row--;
			}
			row++;// last row add 1
		}
	}
	
	private static int ROW = 10;  
	private static int COL = 10;
	private static int [][]result = new int[ROW][COL];//record real value
	private static int [][]initial = new int[ROW][COL];// recod flag, 0 no access, 1 accessed
	private static String[][] directions = new String[ROW][COL];//record direction flag → ↓ ← ↑

}

 

效果图如下

 

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。