对二维数据的一种遍历

代码

	public static void solve(String[][] datas, int rows, int cols, int offset) {

		boolean isReturn = isEnd(rows, cols, offset);

		if (isReturn) {
			return;
		}

		int row_index = offset;
		int col_index = offset;

		int row_max = rows - 1 - offset;
		int col_max = cols - 1 - offset;

		while (col_index <= col_max) {
			System.out.print(datas[row_index][col_index]);
			if (col_index != col_max) {
				col_index++;
			} else {
				break;
			}
		}

		while (row_index < row_max) {
			row_index++;
			System.out.print(datas[row_index][col_index]);

		}

		while (col_index > offset) {
			col_index--;
			System.out.print(datas[row_index][col_index]);
		}

		while (row_index > (offset + 1)) {
			row_index--;
			System.out.print(datas[row_index][col_index]);
		}
		System.out.println("");
		solve(datas, rows, cols, offset + 1);
	}

	private static boolean isEnd(int rows, int cols, int offset) {
		int minSize = rows > cols ? cols : rows;
		if (minSize % 2 == 0) {
			return offset == minSize / 2;
		}
		return (minSize / 2 + 1) == offset;
	}

main 方法

	public static void main(String[] args) {

		String[][] datas1 = 
			{ 
				{ "a", "b", "c", "d", "e" }, 
				{ "f", "g", "h", "i", "j" },
				{ "k", "l", "m", "n", "o" },
				{ "p", "q", "r", "s", "t" },
			};

		String[][] datas2 = 
			{ 
				{ "a", "b", "c" }, 
				{ "f", "g", "h" }, 
				{ "k", "l", "m" }, 
				{ "p", "q", "r" }, 
			};

		String[][] datas3 = 
			{ 
				{ "a", "b", "c", "d", "e" }, 
				{ "f", "g", "h", "i", "j" }, 
				{ "k", "l", "m", "n", "o" },
				{ "p", "q", "r", "s", "t" }, 
				{ "u", "v", "w", "x", "y" } 
			};

		solve(datas1, 4, 5, 0);
		System.out.println("------------------");
		solve(datas2, 4, 3, 0);
		System.out.println("------------------");
		solve(datas3, 5, 5, 0);

	}

输出



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值