【算法基础】转圈打印矩阵

给定的matrix矩阵,由内而外转圈打印元素

核心思想:将矩阵分圈、再循环打印 

package com.javakk.ex;

/**
 * @Time 2018年8月30日 下午3:44:17
 * @Title { 转圈打印矩阵 }
 * @Desc  { 给定的matrix矩阵,由内而外转圈打印元素 }
 * @Email 92920@sohu.com
 * @Author JavaKK
 */
public class Ex12 {

	public static void main(String[] args) {
		int[][] matrix = { 
				{ 1, 2, 3, 8 },
				{ 2, 3, 2, 5 },
				{ 3, 4, 1, 6 },
				{ 4, 5, 0, 7 }
			};
		aroundPrint(matrix);
	}
	
	/**
	 * 将矩阵分圈
	 * @param matrix
	 */
	private static void aroundPrint(int[][] matrix){
		int tR = 0;
		int tC = 0;
		int dR = matrix.length - 1;
		int dC = matrix[0].length - 1;
		while (tR <= dR && tC <= dC) {
			 printEdge(matrix, tR++, tC++, dR--, dC--);
		}
	}
	
	/**
	 * 循环打印
	 * @param matrix
	 * @param tR : 左上row坐标
	 * @param tC : 左上col坐标
	 * @param dR : 右下row坐标
	 * @param dC : 右下col坐标
	 */
	private static void printEdge(int[][] matrix, int tR, int tC, int dR, int dC) {
		if (tR == dR) {
			// 只剩最后一行
			for (int i = tC; i <= dC; i++) {
				System.out.println(matrix[tR][i] + " ");
			}
		} else if (tC == dC) {
			// 只剩最后一列
			for (int i = tR; i <= dR; i++) {
				System.out.println(matrix[i][tC] + " ");
			}
		} else {
			// 一般情况
			int curC = tC;
			int curR = tR;
			while (curC < dC) {
				// 从左到右打印
				System.out.print(matrix[tR][curC] + " ");
				curC++;
			}
			while (curR < dR) {
				// 从上到下打印
				System.out.print(matrix[curR][dC] + " ");
				curR++;
			}
			while (curC > tC) {
				// 从右到左打印
				System.out.print(matrix[dR][curC] + " ");
				curC--;
			}
			while (curR > tR) {
				// 从下到上打印
				System.out.print(matrix[curR][tC] + " ");
				curR--;
			}
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值