对于一个矩阵,请设计一个算法从左上角(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--; } } } }
?
原文:http://hcx2013.iteye.com/blog/2242146