顺时针打印矩阵

对于一个矩阵,请设计一个算法从左上角(mat[0][0])开始,顺时针打印矩阵元素。

给定int矩阵mat,以及它的维数nxm,请返回一个数组,数组中的元素为矩阵元素的顺时针输出。

测试样例:
[[1,2],[3,4]],2,2
返回:[1,2,3,4]


import java.util.*;

public class Printer {
    private static int index = 0;
/*	public static void main(String[] args) {
		int[][] max = {{4,46,89}, {28,66,99}, {26,21,71}};
		int[] clockwisePrint = clockwisePrint(max, 3, 3);
		System.out.println(Arrays.toString(clockwisePrint));
	}*/
	
	public int[] clockwisePrint(int[][] mat, int n, int m) {
		int[] res = new int[mat.length*mat[0].length];
		int tR = 0;
		int tC = 0;
		int dR = mat.length-1;
		int dC = mat[0].length-1;
		
		while (tR <= dR && tC <= dC) {
			solve(mat, tR++, tC++, dR--, dC--, res);
		}
		return res;
	}

	private void solve(int[][] mat, int tR, int tC, int dR, int dC, int[] res) {
		if (tR == dR) {
			for (int i = tC; i <= dC; i++) {
				res[index++] = mat[tR][i];
			}
		} else if (tC == dC) {
			for (int i = tR; i <= dR; i++) {
				res[index++] = mat[i][tC];
			}
		} else {
			int curC = tC;
			int curR = tR;
			while (curC != dC) {
				res[index++] = mat[tR][curC];
				curC++;
			}
			while (curR != dR) {
				res[index++] = mat[curR][dC];
				curR++;
			}
			while (curC != tC) {
				res[index++] = mat[dR][curC];
				curC--;
			}
			while (curR != tR) {
				res[index++] = mat[curR][tC];
				curR--;
			}
		}
	}
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值