标签:try span col list code star static rac 关注
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 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
这道题没什么特殊解法,就是不断的控制循环条件,一点点分析。
一圈一圈的打印矩阵,主要就是画矩阵,找规律,不用在意矩阵的取值,主要关注的是矩阵的坐标。可以选择每一圈矩阵的左上角作为起始点。
import java.util.*; public class test { public static void main(String[] args) { //[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] int[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}}; ArrayList<Integer> integers = null; try { integers = printMatrix(matrix); } catch (Exception e) { e.printStackTrace(); } for (int i = 0; i < integers.size(); i++) { System.out.print(integers.get(i) + ","); } } public static ArrayList<Integer> printMatrix(int[][] matrix) { ArrayList<Integer> resultList = new ArrayList<>(); int rows = matrix.length; int columns = matrix[0].length; if (matrix == null) { return null; } int start = 0; //循环打印每一圈 while (columns > start * 2 && rows > start * 2) { ArrayList<Integer> circleList = printMatrixInCircle(matrix, columns, rows, start); resultList.addAll(circleList); ++start; } return resultList; } public static ArrayList<Integer> printMatrixInCircle(int[][] matrix, int columns, int rows, int start) { ArrayList<Integer> circleList = new ArrayList<>(); int endX = columns - 1 - start;//终止列号 int endY = rows - 1 - start;//终止行号 //从左到右打印 for (int i = start; i <= endX; i++) { int number = matrix[start][i]; circleList.add(number); } //从上到下打印 if (start < endY) { for (int i = start + 1; i <= endY; i++) { int number = matrix[i][endX]; circleList.add(number); } } //从右向左打印 if (start < endX && start < endY) { for (int i = endX - 1; i >= start; i--) { int number = matrix[endY][i]; circleList.add(number); } } //从下到上打印 if (start < endX && start < endY - 1) { for (int i = endY - 1; i >= start + 1; i--) { int number = matrix[i][start]; circleList.add(number); } } return circleList; } }
标签:try span col list code star static rac 关注
原文地址:https://www.cnblogs.com/guoyu1/p/12143376.html