题目描述:
对于一个矩阵,请设计一个算法从左上角(mat[0][0])开始,顺时针打印矩阵元素。
给定int矩阵mat,以及它的维数nxm,请返回一个数组,数组中的元素为矩阵元素的顺时针输出。
测试样例:
[[1,2],[3,4]],2,2
返回:[1,2,4,3]
解题思路:
对于一个矩阵,顺时针打印时一定要保证边界处理的正确性;
解题代码:
public class Printer {
public int[] clockwisePrint(int[][] mat, int n, int m) {
// write code here
// 定义一个返回结果的数组,将顺时针遍历的所有值存下来返回
int[] ret = new int[m*n]; // n为行,m为列
// 判断非法输入的情况
if(n <= 0 || m <= 0)
return ret;
// 定义控制行的下标
int i = 0;
// 定义控制列的下标
int j = 0;
// 定义控制要返回的数组ret的下标
int index = 0;
// 定义圈数,每遍历完一层就 +1
int N = 0;
// 当要返回的数组的下标超过 n*m 时,说明数组已经满了,也就是给定的mat数组中所有的数都已
//经遍历完了,此时结束
while(in