内螺旋数组java实现

最初学习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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值