算法题-循环打印矩阵
要求:给定一个二维数组,按边依次循环打印数组元素。
示例一: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 输出:1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 示例二: 1 2 3 4 5 6 7 8 9 10 11 12 输出:1 2 3 4 8 12 11 10 9 5 6 7 示例三: 1 2 3 4 5 6 7 8 9 10 11 12 输出:1 2 3 6 9 12 11 10 7 4 5 8
代码:
public static void main(String[] args) { int[][] arr = new int[][]{ { 1,2,3,4}, { 5,6,7,8}, { 9,10,11,12},{ 13,14,15,16}}; String res = traverse(arr); System.out.println(res); int[][] a = new int[][]{ { 1,2,3,4}, { 5,6,7,8}, { 9,10,11,12}}; String ares = traverse(a); System.out.println(ares); int[][] b = new int[][]{ { 1,2,3}, { 4,5,6}, { 7,8,9}, { 10,11,12}}; String bres = traverse(b); System.out.println(bres); } public static String traverse(int[][] arr) { int row = arr.length; int cloum = arr[0].length; StringBuffer buffer = new StringBuffer(); for (int s = 0; s < Math.min((row+1)/2,(cloum+1)/2); s++) { int x0 = s; int x1 = row-s; int y0 = s; int y1 = cloum-s; for (int i = x0; i < y1 ; i++) { buffer.append(arr[x0][i]+" "); } if(row-2*s==1){ continue; } for (int i = y0+1; i < x1; i++) { buffer.append(arr[i][y1-1]+" "); } if(cloum-2*s==1){ continue; } for (int i = y1-2; i >= x0; i--) { buffer.append(arr[x1-1][i]+" "); } for (int i = x1-2; i >= y0+1; i--) { buffer.append(arr[i][y0]+" "); } } return buffer.toString().trim(); }