Matrix:The matrix in spiral order

来源:互联网 发布:再见老婆啥软件 编辑:程序博客网 时间:2024/05/28 23:09
/**Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.For example, given the following matrix:[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]You should return [1,2,3,6,9,8,7,4,5].[ [1, 2, 3, 4 ], [5, 6, 7, 8 ], [9, 10,11,12], [13,14,15,16]]You should return [1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10].*/public class SpiralMatrix {public static void main(String[] args) {Integer [][] matrix = new Integer[5][5];matrix[0] = new Integer[]{1,  2,  3,  4,  5};matrix[1] = new Integer[]{6,  7,  8,  9,  10};matrix[2] = new Integer[]{11, 12, 13, 14, 15};matrix[3] = new Integer[]{16, 17, 18, 19, 20};matrix[4] = new Integer[]{21, 22, 23, 24, 25};execute(matrix);}private static void execute(Integer[][] matrix) {//首先算出会循环几圈int width = matrix[0].length;int height = matrix.length;Integer m = width >= height ? width / 2 : height / 2;String s = "[";for(int i = 0; i < m; i++) {int top = i;//上:起始位置int right = i+1; //右:起始位置int down = width-i-2;//下:起始位置int left = height-i-2;//左:起始位置//打印上 s = printTopDown("top", top, width-i-1, 0, i, matrix, s);//打印右s = printRightLeft("right", right, width-i-1, height-i-1, 0, matrix, s);//打印下s = printTopDown("down", down, 0, height, i, matrix, s);//打印左s = printRightLeft("left", left, 0, 0, i, matrix, s);}if(width >= height) {m = width;} else {m = height;}if(0 != m % 2) {s += matrix[m/2][m/2];}s += "]";System.out.println("结果 : " + s);}private static String printRightLeft(String type, int start, int width, int height, int i, Integer[][] matrix, String s) {if(type.equals("right")) {for(; start <= height; start++) {s += matrix[start][width] + ",";}} else {for(; start > i; start--) {s += matrix[start][i] + ",";}}return s;}private static String printTopDown(String type, int start, int width, int height, int i, Integer[][] matrix, String s) {if("top".equals(type)) {for(; start <= width; start++) {s += matrix[i][start] + ",";}} else {for(; start >= i; start--) {s += matrix[height-i-1][start] + ",";}}return s;}}

0 0
原创粉丝点击