給定一個整型矩陣matrix,請按照轉圈的方式打印它。 例如:
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
【要求】 額外空間複雜度爲O(1)。java
//coding=utf8 /***************************************************** @Author: Alex ****************************************************/ public class main{ public static void PrintMatrix(int[][] matrix, int leftRow, int leftColumn, int rightRow, int rightColumn) { if (leftRow == rightRow) { for (int i = leftColumn; i < (rightColumn + 1); i++) System.out.println(matrix[leftRow][i] + " "); } else if (leftColumn == rightColumn) { for (int i = leftRow; i < (rightRow + 1); i++) System.out.println(matrix[i][leftColumn] + " "); } else { int curRow = leftRow, curColumn = leftColumn; for(; curColumn != rightColumn; curColumn++) System.out.println(matrix[leftRow][curColumn] + " "); for(; curRow != rightRow; curRow++) System.out.println(matrix[curRow][rightColumn]); for(; curColumn != leftColumn; curColumn--) System.out.println(matrix[rightRow][curColumn]); for(; curRow != leftRow; curRow--) System.out.println(matrix[curRow][leftColumn]); } } public static void CirclePrintingMatrix(int [][] matrix){ int leftRow = 0, leftColumn = 0; int rightRow = matrix.length - 1, rightColumn = matrix[0].length - 1; while(leftRow < (rightRow + 1) && leftColumn < (rightColumn + 1)) PrintMatrix(matrix, leftRow++, leftColumn++, rightRow--, rightColumn--); } public static void main(String[] args){ int [][] matrix = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16} }; CirclePrintingMatrix(matrix); } }